repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config/src/util_io.dart
// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Utility methods requiring dart:io and used by more than one library in the /// package. library package_config.util_io; import 'dart:io'; import 'dart:typed_data'; Future<Uint8List> defaultLoader(Uri uri) async { if (uri.isScheme("file")) { var file = File.fromUri(uri); try { return await file.readAsBytes(); } catch (_) { return null; } } if (uri.isScheme("http") || uri.isScheme("https")) { return _httpGet(uri); } throw UnsupportedError("Default URI unsupported scheme: $uri"); } Future<Uint8List /*?*/ > _httpGet(Uri uri) async { assert(uri.isScheme("http") || uri.isScheme("https")); var client = HttpClient(); var request = await client.getUrl(uri); var response = await request.close(); if (response.statusCode != HttpStatus.ok) { return null; } var splitContent = await response.toList(); var totalLength = 0; if (splitContent.length == 1) { var part = splitContent[0]; if (part is Uint8List) { return part; } } for (var list in splitContent) { totalLength += list.length; } var result = Uint8List(totalLength); var offset = 0; for (Uint8List contentPart in splitContent) { result.setRange(offset, offset + contentPart.length, contentPart); offset += contentPart.length; } return result; } /// The file name of a path. /// /// The file name is everything after the last occurrence of /// [Platform.pathSeparator], or the entire string if no /// path separator occurs in the string. String fileName(String path) { var separator = Platform.pathSeparator; var lastSeparator = path.lastIndexOf(separator); if (lastSeparator < 0) return path; return path.substring(lastSeparator + separator.length); } /// The directory name of a path. /// /// The directory name is everything before the last occurrence of /// [Platform.pathSeparator], or the empty string if no /// path separator occurs in the string. String dirName(String path) { var separator = Platform.pathSeparator; var lastSeparator = path.lastIndexOf(separator); if (lastSeparator < 0) return ""; return path.substring(0, lastSeparator); } /// Join path parts with the [Platform.pathSeparator]. /// /// If a part ends with a path separator, then no extra separator is /// inserted. String pathJoin(String part1, String part2, [String part3]) { var separator = Platform.pathSeparator; var separator1 = part1.endsWith(separator) ? "" : separator; if (part3 == null) { return "$part1$separator1$part2"; } var separator2 = part2.endsWith(separator) ? "" : separator; return "$part1$separator1$part2$separator2$part3"; } /// Join an unknown number of path parts with [Platform.pathSeparator]. /// /// If a part ends with a path separator, then no extra separator is /// inserted. String pathJoinAll(Iterable<String> parts) { var buffer = StringBuffer(); var separator = ""; for (var part in parts) { buffer..write(separator)..write(part); separator = part.endsWith(Platform.pathSeparator) ? "" : Platform.pathSeparator; } return buffer.toString(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config/src/packages_io_impl.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Implementations of [Packages] that can only be used in server based /// applications. @Deprecated("Use the package_config.json based API") library package_config.packages_io_impl; import "dart:collection" show UnmodifiableMapView; import "dart:io" show Directory; import "packages_impl.dart"; import "util_io.dart"; /// A [Packages] implementation based on a local directory. class FilePackagesDirectoryPackages extends PackagesBase { final Directory _packageDir; final Map<String, Uri> _packageToBaseUriMap = <String, Uri>{}; FilePackagesDirectoryPackages(this._packageDir); Uri getBase(String packageName) { return _packageToBaseUriMap.putIfAbsent(packageName, () { return Uri.file(pathJoin(_packageDir.path, packageName, '.')); }); } Iterable<String> _listPackageNames() { return _packageDir .listSync() .whereType<Directory>() .map((e) => fileName(e.path)); } Iterable<String> get packages => _listPackageNames(); Map<String, Uri> asMap() { var result = <String, Uri>{}; for (var packageName in _listPackageNames()) { result[packageName] = getBase(packageName); } return UnmodifiableMapView<String, Uri>(result); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config/src/package_config.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:typed_data'; import 'errors.dart'; import "package_config_impl.dart"; import 'package_config_json.dart'; /// A package configuration. /// /// Associates configuration data to packages and files in packages. /// /// More members may be added to this class in the future, /// so classes outside of this package must not implement [PackageConfig] /// or any subclass of it. abstract class PackageConfig { /// The largest configuration version currently recognized. static const int maxVersion = 2; /// An empty package configuration. /// /// A package configuration with no available packages. /// Is used as a default value where a package configuration /// is expected, but none have been specified or found. static const PackageConfig empty = SimplePackageConfig.empty(); /// Creats a package configuration with the provided available [packages]. /// /// The packages must be valid packages (valid package name, valid /// absolute directory URIs, valid language version, if any), /// and there must not be two packages with the same name. /// /// The package's root ([Package.rootUri]) and package-root /// ([Package.packageUriRoot]) paths must satisfy a number of constraints /// We say that one path (which we know ends with a `/` charater) /// is inside another path, if the latter path is a prefix of the former path, /// including the two paths being the same. /// /// * No package's root must be the same as another package's root. /// * The package-root of a package must be inside the pacakge's root. /// * If one package's package-root is inside another package's root, /// then the latter package's package root must not be inside the former /// package's root. (No getting between a package and its package root!) /// This also disallows a package's root being the same as another /// package's package root. /// /// If supplied, the [extraData] will be available as the /// [PackageConfig.extraData] of the created configuration. /// /// The version of the resulting configuration is always [maxVersion]. factory PackageConfig(Iterable<Package> packages, {dynamic extraData}) => SimplePackageConfig(maxVersion, packages, extraData); /// Parses a package configuration file. /// /// The [bytes] must be an UTF-8 encoded JSON object /// containing a valid package configuration. /// /// The [baseUri] is used as the base for resolving relative /// URI references in the configuration file. If the configuration /// has been read from a file, the [baseUri] can be the URI of that /// file, or of the directory it occurs in. /// /// If [onError] is provided, errors found during parsing or building /// the configuration are reported by calling [onError] instead of /// throwing, and parser makes a *best effort* attempt to continue /// despite the error. The input must still be valid JSON. /// The result may be a [PackageConfig.empty] if there is no way to /// extract useful information from the bytes. static PackageConfig parseBytes(Uint8List bytes, Uri baseUri, {void onError(Object error)}) => parsePackageConfigBytes(bytes, baseUri, onError ?? throwError); /// Parses a package configuration file. /// /// The [configuration] must be a JSON object /// containing a valid package configuration. /// /// The [baseUri] is used as the base for resolving relative /// URI references in the configuration file. If the configuration /// has been read from a file, the [baseUri] can be the URI of that /// file, or of the directory it occurs in. /// /// If [onError] is provided, errors found during parsing or building /// the configuration are reported by calling [onError] instead of /// throwing, and parser makes a *best effort* attempt to continue /// despite the error. The input must still be valid JSON. /// The result may be a [PackageConfig.empty] if there is no way to /// extract useful information from the bytes. static PackageConfig parseString(String configuration, Uri baseUri, {void onError(Object error)}) => parsePackageConfigString(configuration, baseUri, onError ?? throwError); /// Parses the JSON data of a package configuration file. /// /// The [configuration] must be a JSON-like Dart data structure, /// like the one provided by parsing JSON text using `dart:convert`, /// containing a valid package configuration. /// /// The [baseUri] is used as the base for resolving relative /// URI references in the configuration file. If the configuration /// has been read from a file, the [baseUri] can be the URI of that /// file, or of the directory it occurs in. /// /// If [onError] is provided, errors found during parsing or building /// the configuration are reported by calling [onError] instead of /// throwing, and parser makes a *best effort* attempt to continue /// despite the error. The input must still be valid JSON. /// The result may be a [PackageConfig.empty] if there is no way to /// extract useful information from the bytes. static PackageConfig parseJson(dynamic jsonData, Uri baseUri, {void onError(Object error)}) => parsePackageConfigJson(jsonData, baseUri, onError ?? throwError); /// Writes a configuration file for this configuration on [output]. /// /// If [baseUri] is provided, URI references in the generated file /// will be made relative to [baseUri] where possible. static void writeBytes(PackageConfig configuration, Sink<Uint8List> output, [Uri /*?*/ baseUri]) { writePackageConfigJsonUtf8(configuration, baseUri, output); } /// Writes a configuration JSON text for this configuration on [output]. /// /// If [baseUri] is provided, URI references in the generated file /// will be made relative to [baseUri] where possible. static void writeString(PackageConfig configuration, StringSink output, [Uri /*?*/ baseUri]) { writePackageConfigJsonString(configuration, baseUri, output); } /// Converts a configuration to a JSON-like data structure. /// /// If [baseUri] is provided, URI references in the generated data /// will be made relative to [baseUri] where possible. static Map<String, dynamic> toJson(PackageConfig configuration, [Uri /*?*/ baseUri]) => packageConfigToJson(configuration, baseUri); /// The configuration version number. /// /// Currently this is 1 or 2, where /// * Version one is the `.packages` file format and /// * Version two is the first `package_config.json` format. /// /// Instances of this class supports both, and the version /// is only useful for detecting which kind of file the configuration /// was read from. int get version; /// All the available packages of this configuration. /// /// No two of these packages have the same name, /// and no two [Package.root] directories overlap. Iterable<Package> get packages; /// Look up a package by name. /// /// Returns the [Package] fron [packages] with [packageName] as /// [Package.name]. Returns `null` if the package is not available in the /// current configuration. Package /*?*/ operator [](String packageName); /// Provides the associated package for a specific [file] (or directory). /// /// Returns a [Package] which contains the [file]'s path, if any. /// That is, the [Package.rootUri] directory is a parent directory /// of the [file]'s location. /// /// Returns `null` if the file does not belong to any package. Package /*?*/ packageOf(Uri file); /// Resolves a `package:` URI to a non-package URI /// /// The [packageUri] must be a valid package URI. That means: /// * A URI with `package` as scheme, /// * with no authority part (`package://...`), /// * with a path starting with a valid package name followed by a slash, and /// * with no query or fragment part. /// /// Throws an [ArgumentError] (which also implements [PackageConfigError]) /// if the package URI is not valid. /// /// Returns `null` if the package name of [packageUri] is not available /// in this package configuration. /// Returns the remaining path of the package URI resolved relative to the /// [Package.packageUriRoot] of the corresponding package. Uri /*?*/ resolve(Uri packageUri); /// The package URI which resolves to [nonPackageUri]. /// /// The [nonPackageUri] must not have any query or fragment part, /// and it must not have `package` as scheme. /// Throws an [ArgumentError] (which also implements [PackageConfigError]) /// if the non-package URI is not valid. /// /// Returns a package URI which [resolve] will convert to [nonPackageUri], /// if any such URI exists. Returns `null` if no such package URI exists. Uri /*?*/ toPackageUri(Uri nonPackageUri); /// Extra data associated with the package configuration. /// /// The data may be in any format, depending on who introduced it. /// The standard `packjage_config.json` file storage will only store /// JSON-like list/map data structures. dynamic get extraData; } /// Configuration data for a single package. abstract class Package { /// Creates a package with the provided properties. /// /// The [name] must be a valid package name. /// The [root] must be an absolute directory URI, meaning an absolute URI /// with no query or fragment path and a path starting and ending with `/`. /// The [packageUriRoot], if provided, must be either an absolute /// directory URI or a relative URI reference which is then resolved /// relative to [root]. It must then also be a subdirectory of [root], /// or the same directory, and must end with `/`. /// If [languageVersion] is supplied, it must be a valid Dart language /// version, which means two decimal integer literals separated by a `.`, /// where the integer literals have no leading zeros unless they are /// a single zero digit. /// If [extraData] is supplied, it will be available as the /// [Package.extraData] of the created package. factory Package(String name, Uri root, {Uri /*?*/ packageUriRoot, LanguageVersion /*?*/ languageVersion, dynamic extraData}) => SimplePackage.validate( name, root, packageUriRoot, languageVersion, extraData, throwError); /// The package-name of the package. String get name; /// The location of the root of the package. /// /// Is always an absolute URI with no query or fragment parts, /// and with a path ending in `/`. /// /// All files in the [rootUri] directory are considered /// part of the package for purposes where that that matters. Uri get root; /// The root of the files available through `package:` URIs. /// /// A `package:` URI with [name] as the package name is /// resolved relative to this location. /// /// Is always an absolute URI with no query or fragment part /// with a path ending in `/`, /// and with a location which is a subdirectory /// of the [root], or the same as the [root]. Uri get packageUriRoot; /// The default language version associated with this package. /// /// Each package may have a default language version associated, /// which is the language version used to parse and compile /// Dart files in the package. /// A package version is defined by two non-negative numbers, /// the *major* and *minor* version numbers. LanguageVersion /*?*/ get languageVersion; /// Extra data associated with the specific package. /// /// The data may be in any format, depending on who introduced it. /// The standard `packjage_config.json` file storage will only store /// JSON-like list/map data structures. dynamic get extraData; } /// A language version. /// /// A language version is represented by two non-negative integers, /// the [major] and [minor] version numbers. /// /// If errors during parsing are handled using an `onError` handler, /// then an *invalid* language version may be represented by an /// [InvalidLanguageVersion] object. abstract class LanguageVersion implements Comparable<LanguageVersion> { /// The maximal value allowed by [major] and [minor] values; static const int maxValue = 0x7FFFFFFF; factory LanguageVersion(int major, int minor) { RangeError.checkValueInInterval(major, 0, maxValue, "major"); RangeError.checkValueInInterval(minor, 0, maxValue, "major"); return SimpleLanguageVersion(major, minor, null); } /// Parses a language version string. /// /// A valid language version string has the form /// /// > *decimalNumber* `.` *decimalNumber* /// /// where a *decimalNumber* is a non-empty sequence of decimal digits /// with no unnecessary leading zeros (the decimal number only starts /// with a zero digit if that digit is the entire number). /// No spaces are allowed in the string. /// /// If the [source] is valid then it is parsed into a valid /// [LanguageVersion] object. /// If not, then the [onError] is called with a [FormatException]. /// If [onError] is not supplied, it defaults to throwing the exception. /// If the call does not throw, then an [InvalidLanguageVersion] is returned /// containing the original [source]. static LanguageVersion parse(String source, {void onError(Object error)}) => parseLanguageVersion(source, onError ?? throwError); /// The major language version. /// /// A non-negative integer less than 2<sup>31</sup>. /// /// The value is negative for objects representing *invalid* language /// versions ([InvalidLanguageVersion]). int get major; /// The minor language version. /// /// A non-negative integer less than 2<sup>31</sup>. /// /// The value is negative for objects representing *invalid* language /// versions ([InvalidLanguageVersion]). int get minor; /// Compares language versions. /// /// Two language versions are considered equal if they have the /// same major and minor version numbers. /// /// A language version is greater then another if the former's major version /// is greater than the latter's major version, or if they have /// the same major version and the former's minor version is greater than /// the latter's. int compareTo(LanguageVersion other); /// Valid language versions with the same [major] and [minor] values are /// equal. /// /// Invalid language versions ([InvalidLanguageVersion]) are not equal to /// any other object. bool operator ==(Object other); int get hashCode; /// A string representation of the language version. /// /// A valid language version is represented as /// `"${version.major}.${version.minor}"`. String toString(); } /// An *invalid* language version. /// /// Stored in a [Package] when the orginal language version string /// was invalid and a `onError` handler was passed to the parser /// which did not throw on an error. abstract class InvalidLanguageVersion implements LanguageVersion { /// The value -1 for an invalid language version. int get major; /// The value -1 for an invalid language version. int get minor; /// An invalid language version is only equal to itself. bool operator ==(Object other); int get hashCode; /// The original invalid version string. String toString(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config/src/discovery.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import "dart:io"; import 'dart:typed_data'; import 'package_config_io.dart'; import "errors.dart"; import "package_config_impl.dart"; import "package_config_json.dart"; import "packages_file.dart" as packages_file; import "util_io.dart" show defaultLoader, pathJoin; final Uri packageConfigJsonPath = Uri(path: ".dart_tool/package_config.json"); final Uri dotPackagesPath = Uri(path: ".packages"); final Uri currentPath = Uri(path: "."); final Uri parentPath = Uri(path: ".."); /// Discover the package configuration for a Dart script. /// /// The [baseDirectory] points to the directory of the Dart script. /// A package resolution strategy is found by going through the following steps, /// and stopping when something is found. /// /// * Check if a `.dart_tool/package_config.json` file exists in the directory. /// * Check if a `.packages` file exists in the directory. /// * Repeat these checks for the parent directories until reaching the /// root directory if [recursive] is true. /// /// If any of these tests succeed, a `PackageConfig` class is returned. /// Returns `null` if no configuration was found. If a configuration /// is needed, then the caller can supply [PackageConfig.empty]. Future<PackageConfig /*?*/ > findPackageConfig( Directory baseDirectory, bool recursive, void onError(Object error)) async { var directory = baseDirectory; if (!directory.isAbsolute) directory = directory.absolute; if (!await directory.exists()) { return null; } do { // Check for $cwd/.packages var packageConfig = await findPackagConfigInDirectory(directory, onError); if (packageConfig != null) return packageConfig; if (!recursive) break; // Check in parent directories. var parentDirectory = directory.parent; if (parentDirectory.path == directory.path) break; directory = parentDirectory; } while (true); return null; } /// Similar to [findPackageConfig] but based on a URI. Future<PackageConfig /*?*/ > findPackageConfigUri( Uri location, Future<Uint8List /*?*/ > loader(Uri uri) /*?*/, void onError(Object error) /*?*/, bool recursive) async { if (location.isScheme("package")) { onError(PackageConfigArgumentError( location, "location", "Must not be a package: URI")); return null; } if (loader == null) { if (location.isScheme("file")) { return findPackageConfig( Directory.fromUri(location.resolveUri(currentPath)), recursive, onError); } loader = defaultLoader; } if (!location.path.endsWith("/")) location = location.resolveUri(currentPath); while (true) { var file = location.resolveUri(packageConfigJsonPath); var bytes = await loader(file); if (bytes != null) { return parsePackageConfigBytes(bytes, file, onError); } file = location.resolveUri(dotPackagesPath); bytes = await loader(file); if (bytes != null) { return packages_file.parse(bytes, file, onError); } if (!recursive) break; var parent = location.resolveUri(parentPath); if (parent == location) break; location = parent; } return null; } /// Finds a `.packages` or `.dart_tool/package_config.json` file in [directory]. /// /// Loads the file, if it is there, and returns the resulting [PackageConfig]. /// Returns `null` if the file isn't there. /// Reports a [FormatException] if a file is there but the content is not valid. /// If the file exists, but fails to be read, the file system error is reported. /// /// If [onError] is supplied, parsing errors are reported using that, and /// a best-effort attempt is made to return a package configuration. /// This may be the empty package configuration. Future<PackageConfig /*?*/ > findPackagConfigInDirectory( Directory directory, void onError(Object error)) async { var packageConfigFile = await checkForPackageConfigJsonFile(directory); if (packageConfigFile != null) { return await readPackageConfigJsonFile(packageConfigFile, onError); } packageConfigFile = await checkForDotPackagesFile(directory); if (packageConfigFile != null) { return await readDotPackagesFile(packageConfigFile, onError); } return null; } Future<File> /*?*/ checkForPackageConfigJsonFile(Directory directory) async { assert(directory.isAbsolute); var file = File(pathJoin(directory.path, ".dart_tool", "package_config.json")); if (await file.exists()) return file; return null; } Future<File /*?*/ > checkForDotPackagesFile(Directory directory) async { var file = File(pathJoin(directory.path, ".packages")); if (await file.exists()) return file; return null; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config/src/errors.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// General superclass of most errors and exceptions thrown by this package. /// /// Only covers errors thrown while parsing package configuration files. /// Programming errors and I/O exceptions are not covered. abstract class PackageConfigError { PackageConfigError._(); } class PackageConfigArgumentError extends ArgumentError implements PackageConfigError { PackageConfigArgumentError(Object /*?*/ value, String name, String message) : super.value(value, name, message); PackageConfigArgumentError.from(ArgumentError error) : super.value(error.invalidValue, error.name, error.message); } class PackageConfigFormatException extends FormatException implements PackageConfigError { PackageConfigFormatException(String message, Object /*?*/ source, [int /*?*/ offset]) : super(message, source, offset); PackageConfigFormatException.from(FormatException exception) : super(exception.message, exception.source, exception.offset); } /// The default `onError` handler. void /*Never*/ throwError(Object error) => throw error;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config/src/package_config_json.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // Parsing and serialization of package configurations. import "dart:convert"; import "dart:typed_data"; import "errors.dart"; import "package_config_impl.dart"; import "packages_file.dart" as packages_file; import "util.dart"; const String _configVersionKey = "configVersion"; const String _packagesKey = "packages"; const List<String> _topNames = [_configVersionKey, _packagesKey]; const String _nameKey = "name"; const String _rootUriKey = "rootUri"; const String _packageUriKey = "packageUri"; const String _languageVersionKey = "languageVersion"; const List<String> _packageNames = [ _nameKey, _rootUriKey, _packageUriKey, _languageVersionKey ]; const String _generatedKey = "generated"; const String _generatorKey = "generator"; const String _generatorVersionKey = "generatorVersion"; final _jsonUtf8Decoder = json.fuse(utf8).decoder; PackageConfig parsePackageConfigBytes( Uint8List bytes, Uri file, void onError(Object error)) { // TODO(lrn): Make this simpler. Maybe parse directly from bytes. var jsonObject; try { jsonObject = _jsonUtf8Decoder.convert(bytes); } on FormatException catch (e) { onError(PackageConfigFormatException.from(e)); return const SimplePackageConfig.empty(); } return parsePackageConfigJson(jsonObject, file, onError); } PackageConfig parsePackageConfigString( String source, Uri file, void onError(Object error)) { var jsonObject; try { jsonObject = jsonDecode(source); } on FormatException catch (e) { onError(PackageConfigFormatException.from(e)); return const SimplePackageConfig.empty(); } return parsePackageConfigJson(jsonObject, file, onError); } /// Creates a [PackageConfig] from a parsed JSON-like object structure. /// /// The [json] argument must be a JSON object (`Map<String, dynamic>`) /// containing a `"configVersion"` entry with an integer value in the range /// 1 to [PackageConfig.maxVersion], /// and with a `"packages"` entry which is a JSON array (`List<dynamic>`) /// containing JSON objects which each has the following properties: /// /// * `"name"`: The package name as a string. /// * `"rootUri"`: The root of the package as a URI stored as a string. /// * `"packageUri"`: Optionally the root of for `package:` URI resolution /// for the package, as a relative URI below the root URI /// stored as a string. /// * `"languageVersion"`: Optionally a language version string which is a /// an integer numeral, a decimal point (`.`) and another integer numeral, /// where the integer numeral cannot have a sign, and can only have a /// leading zero if the entire numeral is a single zero. /// /// All other properties are stored in [extraData]. /// /// The [baseLocation] is used as base URI to resolve the "rootUri" /// URI referencestring. PackageConfig parsePackageConfigJson( dynamic json, Uri baseLocation, void onError(Object error)) { if (!baseLocation.hasScheme || baseLocation.isScheme("package")) { throw PackageConfigArgumentError(baseLocation.toString(), "baseLocation", "Must be an absolute non-package: URI"); } if (!baseLocation.path.endsWith("/")) { baseLocation = baseLocation.resolveUri(Uri(path: ".")); } String typeName<T>() { if (0 is T) return "int"; if ("" is T) return "string"; if (const [] is T) return "array"; return "object"; } T checkType<T>(dynamic value, String name, [String /*?*/ packageName]) { if (value is T) return value; // The only types we are called with are [int], [String], [List<dynamic>] // and Map<String, dynamic>. Recognize which to give a better error message. var message = "$name${packageName != null ? " of package $packageName" : ""}" " is not a JSON ${typeName<T>()}"; onError(PackageConfigFormatException(message, value)); return null; } Package /*?*/ parsePackage(Map<String, dynamic> entry) { String /*?*/ name; String /*?*/ rootUri; String /*?*/ packageUri; String /*?*/ languageVersion; Map<String, dynamic> /*?*/ extraData; var hasName = false; var hasRoot = false; var hasVersion = false; entry.forEach((key, value) { switch (key) { case _nameKey: hasName = true; name = checkType<String>(value, _nameKey); break; case _rootUriKey: hasRoot = true; rootUri = checkType<String>(value, _rootUriKey, name); break; case _packageUriKey: packageUri = checkType<String>(value, _packageUriKey, name); break; case _languageVersionKey: hasVersion = true; languageVersion = checkType<String>(value, _languageVersionKey, name); break; default: (extraData ??= {})[key] = value; break; } }); if (!hasName) { onError(PackageConfigFormatException("Missing name entry", entry)); } if (!hasRoot) { onError(PackageConfigFormatException("Missing rootUri entry", entry)); } if (name == null || rootUri == null) return null; var root = baseLocation.resolve(rootUri); if (!root.path.endsWith("/")) root = root.replace(path: root.path + "/"); var packageRoot = root; if (packageUri != null) packageRoot = root.resolve(packageUri); if (!packageRoot.path.endsWith("/")) { packageRoot = packageRoot.replace(path: packageRoot.path + "/"); } LanguageVersion /*?*/ version; if (languageVersion != null) { version = parseLanguageVersion(languageVersion, onError); } else if (hasVersion) { version = SimpleInvalidLanguageVersion("invalid"); } return SimplePackage.validate(name, root, packageRoot, version, extraData, (error) { if (error is ArgumentError) { onError( PackageConfigFormatException(error.message, error.invalidValue)); } else { onError(error); } }); } var map = checkType<Map<String, dynamic>>(json, "value"); if (map == null) return const SimplePackageConfig.empty(); Map<String, dynamic> /*?*/ extraData; List<Package> /*?*/ packageList; int /*?*/ configVersion; map.forEach((key, value) { switch (key) { case _configVersionKey: configVersion = checkType<int>(value, _configVersionKey) ?? 2; break; case _packagesKey: var packageArray = checkType<List<dynamic>>(value, _packagesKey) ?? []; var packages = <Package>[]; for (var package in packageArray) { var packageMap = checkType<Map<String, dynamic>>(package, "package entry"); if (packageMap != null) { var entry = parsePackage(packageMap); if (entry != null) { packages.add(entry); } } } packageList = packages; break; default: (extraData ??= {})[key] = value; break; } }); if (configVersion == null) { onError(PackageConfigFormatException("Missing configVersion entry", json)); configVersion = 2; } if (packageList == null) { onError(PackageConfigFormatException("Missing packages list", json)); packageList = []; } return SimplePackageConfig(configVersion, packageList, extraData, (error) { if (error is ArgumentError) { onError(PackageConfigFormatException(error.message, error.invalidValue)); } else { onError(error); } }); } final _jsonUtf8Encoder = JsonUtf8Encoder(" "); void writePackageConfigJsonUtf8( PackageConfig config, Uri baseUri, Sink<List<int>> output) { // Can be optimized. var data = packageConfigToJson(config, baseUri); output.add(_jsonUtf8Encoder.convert(data) as Uint8List); } void writePackageConfigJsonString( PackageConfig config, Uri baseUri, StringSink output) { // Can be optimized. var data = packageConfigToJson(config, baseUri); output.write(JsonEncoder.withIndent(" ").convert(data) as Uint8List); } Map<String, dynamic> packageConfigToJson(PackageConfig config, Uri baseUri) => <String, dynamic>{ ...?_extractExtraData(config.extraData, _topNames), _configVersionKey: PackageConfig.maxVersion, _packagesKey: [ for (var package in config.packages) <String, dynamic>{ _nameKey: package.name, _rootUriKey: relativizeUri(package.root, baseUri).toString(), if (package.root != package.packageUriRoot) _packageUriKey: relativizeUri(package.packageUriRoot, package.root) .toString(), if (package.languageVersion != null && package.languageVersion is! InvalidLanguageVersion) _languageVersionKey: package.languageVersion.toString(), ...?_extractExtraData(package.extraData, _packageNames), } ], }; void writeDotPackages(PackageConfig config, Uri baseUri, StringSink output) { var extraData = config.extraData; // Write .packages too. String /*?*/ comment; if (extraData != null) { String /*?*/ generator = extraData[_generatorKey]; if (generator != null) { String /*?*/ generated = extraData[_generatedKey]; String /*?*/ generatorVersion = extraData[_generatorVersionKey]; comment = "Generated by $generator" "${generatorVersion != null ? " $generatorVersion" : ""}" "${generated != null ? " on $generated" : ""}."; } } packages_file.write(output, config, baseUri: baseUri, comment: comment); } /// If "extraData" is a JSON map, then return it, otherwise return null. /// /// If the value contains any of the [reservedNames] for the current context, /// entries with that name in the extra data are dropped. Map<String, dynamic> /*?*/ _extractExtraData( dynamic data, Iterable<String> reservedNames) { if (data is Map<String, dynamic>) { if (data.isEmpty) return null; for (var name in reservedNames) { if (data.containsKey(name)) { data = { for (var key in data.keys) if (!reservedNames.contains(key)) key: data[key] }; if (data.isEmpty) return null; for (var value in data.values) { if (!_validateJson(value)) return null; } } } return data; } return null; } /// Checks that the object is a valid JSON-like data structure. bool _validateJson(dynamic object) { if (object == null || true == object || false == object) return true; if (object is num || object is String) return true; if (object is List<dynamic>) { return object.every(_validateJson); } if (object is Map<String, dynamic>) { return object.values.every(_validateJson); } return false; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/package_config/src/package_config_io.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // dart:io dependent functionality for reading and writing configuration files. import "dart:convert"; import "dart:io"; import "dart:typed_data"; import "discovery.dart" show packageConfigJsonPath; import "errors.dart"; import "package_config_impl.dart"; import "package_config_json.dart"; import "packages_file.dart" as packages_file; import "util.dart"; import "util_io.dart"; /// Reads a package configuration file. /// /// Detects whether the [file] is a version one `.packages` file or /// a version two `package_config.json` file. /// /// If the [file] is a `.packages` file and [preferNewest] is true, /// first checks whether there is an adjacent `.dart_tool/package_config.json` /// file, and if so, reads that instead. /// If [preferNewset] is false, the specified file is loaded even if it is /// a `.packages` file and there is an available `package_config.json` file. /// /// The file must exist and be a normal file. Future<PackageConfig> readAnyConfigFile( File file, bool preferNewest, void onError(Object error)) async { if (preferNewest && fileName(file.path) == ".packages") { var alternateFile = File(pathJoin(dirName(file.path), ".dart_tool", "package_config.json")); if (alternateFile.existsSync()) { return await readPackageConfigJsonFile(alternateFile, onError); } } Uint8List bytes; try { bytes = await file.readAsBytes(); } catch (e) { onError(e); return const SimplePackageConfig.empty(); } return parseAnyConfigFile(bytes, file.uri, onError); } /// Like [readAnyConfigFile] but uses a URI and an optional loader. Future<PackageConfig> readAnyConfigFileUri( Uri file, Future<Uint8List /*?*/ > loader(Uri uri) /*?*/, void onError(Object error), bool preferNewest) async { if (file.isScheme("package")) { throw PackageConfigArgumentError( file, "file", "Must not be a package: URI"); } if (loader == null) { if (file.isScheme("file")) { return await readAnyConfigFile(File.fromUri(file), preferNewest, onError); } loader = defaultLoader; } if (preferNewest && file.pathSegments.last == ".packages") { var alternateFile = file.resolve(".dart_tool/package_config.json"); Uint8List /*?*/ bytes; try { bytes = await loader(alternateFile); } catch (e) { onError(e); return const SimplePackageConfig.empty(); } if (bytes != null) { return parsePackageConfigBytes(bytes, alternateFile, onError); } } Uint8List /*?*/ bytes; try { bytes = await loader(file); } catch (e) { onError(e); return const SimplePackageConfig.empty(); } if (bytes == null) { onError(PackageConfigArgumentError( file.toString(), "file", "File cannot be read")); return const SimplePackageConfig.empty(); } return parseAnyConfigFile(bytes, file, onError); } /// Parses a `.packages` or `package_config.json` file's contents. /// /// Assumes it's a JSON file if the first non-whitespace character /// is `{`, otherwise assumes it's a `.packages` file. PackageConfig parseAnyConfigFile( Uint8List bytes, Uri file, void onError(Object error)) { var firstChar = firstNonWhitespaceChar(bytes); if (firstChar != $lbrace) { // Definitely not a JSON object, probably a .packages. return packages_file.parse(bytes, file, onError); } return parsePackageConfigBytes(bytes, file, onError); } Future<PackageConfig> readPackageConfigJsonFile( File file, void onError(Object error)) async { Uint8List bytes; try { bytes = await file.readAsBytes(); } catch (error) { onError(error); return const SimplePackageConfig.empty(); } return parsePackageConfigBytes(bytes, file.uri, onError); } Future<PackageConfig> readDotPackagesFile( File file, void onError(Object error)) async { Uint8List bytes; try { bytes = await file.readAsBytes(); } catch (error) { onError(error); return const SimplePackageConfig.empty(); } return packages_file.parse(bytes, file.uri, onError); } Future<void> writePackageConfigJsonFile( PackageConfig config, Directory targetDirectory) async { // Write .dart_tool/package_config.json first. var file = File(pathJoin(targetDirectory.path, ".dart_tool", "package_config.json")); var baseUri = file.uri; var sink = file.openWrite(encoding: utf8); writePackageConfigJsonUtf8(config, baseUri, sink); var doneJson = sink.close(); // Write .packages too. file = File(pathJoin(targetDirectory.path, ".packages")); baseUri = file.uri; sink = file.openWrite(encoding: utf8); writeDotPackages(config, baseUri, sink); var donePackages = sink.close(); await Future.wait([doneJson, donePackages]); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/collection.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Collection classes and related utilities. library quiver.collection; export 'src/collection/bimap.dart'; export 'src/collection/delegates/iterable.dart'; export 'src/collection/delegates/list.dart'; export 'src/collection/delegates/map.dart'; export 'src/collection/delegates/queue.dart'; export 'src/collection/delegates/set.dart'; export 'src/collection/lru_map.dart'; export 'src/collection/multimap.dart'; export 'src/collection/treeset.dart'; /// Checks [List]s [a] and [b] for equality. /// /// Returns `true` if [a] and [b] are both null, or they are the same length /// and every element of [a] is equal to the corresponding element at the same /// index in [b]. bool listsEqual(List a, List b) { if (a == b) return true; if (a == null || b == null) return false; if (a.length != b.length) return false; for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) return false; } return true; } /// Checks [Map]s [a] and [b] for equality. /// /// Returns `true` if [a] and [b] are both null, or they are the same length /// and every key `k` in [a] exists in [b] and the values `a[k] == b[k]`. bool mapsEqual(Map a, Map b) { if (a == b) return true; if (a == null || b == null) return false; if (a.length != b.length) return false; for (final k in a.keys) { var bValue = b[k]; if (bValue == null && !b.containsKey(k)) return false; if (bValue != a[k]) return false; } return true; } /// Checks [Set]s [a] and [b] for equality. /// /// Returns `true` if [a] and [b] are both null, or they are the same length and /// every element in [b] exists in [a]. bool setsEqual(Set a, Set b) { if (a == b) return true; if (a == null || b == null) return false; if (a.length != b.length) return false; return a.containsAll(b); } /// Returns the index of the first item in [elements] where [predicate] /// evaluates to true. /// /// Returns -1 if there are no items where [predicate] evaluates to true. int indexOf<T>(Iterable<T> elements, bool predicate(T element)) { if (elements is List<T>) { for (int i = 0; i < elements.length; i++) { if (predicate(elements[i])) return i; } return -1; } int i = 0; for (final element in elements) { if (predicate(element)) return i; i++; } return -1; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/core.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Simple code with broad use cases. library quiver.core; export 'src/core/hash.dart'; export 'src/core/optional.dart'; /// Returns the first non-null argument. /// /// If all arguments are null, throws an [ArgumentError]. /// /// Users of Dart SDK 2.1 or later should prefer: /// /// var value = o1 ?? o2 ?? o3 ?? o4; /// ArgumentError.checkNotNull(value); /// /// If [o1] is an [Optional], this can be accomplished with `o1.or(o2)`. dynamic firstNonNull(o1, o2, [o3, o4]) { // TODO(cbracken): make this generic. if (o1 != null) return o1; if (o2 != null) return o2; if (o3 != null) return o3; if (o4 != null) return o4; throw ArgumentError('All arguments were null'); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/time.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. library quiver.time; export 'src/time/clock.dart'; export 'src/time/duration_unit_constants.dart'; export 'src/time/util.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/iterables.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. library quiver.iterables; export 'src/iterables/concat.dart'; export 'src/iterables/count.dart'; export 'src/iterables/cycle.dart'; export 'src/iterables/enumerate.dart'; export 'src/iterables/generating_iterable.dart'; export 'src/iterables/infinite_iterable.dart'; export 'src/iterables/merge.dart'; export 'src/iterables/min_max.dart'; export 'src/iterables/partition.dart'; export 'src/iterables/range.dart'; export 'src/iterables/zip.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/check.dart
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// A simple set of pre/post-condition checkers based on the /// [Guava](https://code.google.com/p/guava-libraries/) Preconditions /// class in Java. /// /// These checks are stronger than 'assert' statements, which can be /// switched off, so they must only be used in situations where we actively /// want the program to break when the check fails. /// /// ## Performance /// Performance may be an issue with these checks if complex logic is computed /// in order to make the method call. You should be careful with its use in /// these cases - this library is aimed at improving maintainability and /// readability rather than performance. They are also useful when the program /// should fail early - for example, null-checking a parameter that might not /// be used until the end of the method call. /// /// ## Error messages /// The message parameter can be either a `() => Object` or any other `Object`. /// The object will be converted to an error message by calling its /// `toString()`. The `Function` should be preferred if the message is complex /// to construct (i.e., it uses `String` interpolation), because it is only /// called when the check fails. /// /// If the message parameter is `null` or returns `null`, a default error /// message will be used. library quiver.check; /// Throws an [ArgumentError] if the given [expression] is `false`. void checkArgument(bool expression, {message}) { if (!expression) { throw ArgumentError(_resolveMessage(message, null)); } } /// Throws a [RangeError] if the given [index] is not a valid index for a list /// with [size] elements. Otherwise, returns the [index] parameter. int checkListIndex(int index, int size, {message}) { if (index < 0 || index >= size) { throw RangeError(_resolveMessage( message, 'index $index not valid for list of size $size')); } return index; } /// Throws an [ArgumentError] if the given [reference] is `null`. Otherwise, /// returns the [reference] parameter. /// /// Users of Dart SDK 2.1 or later should prefer [ArgumentError.checkNotNull]. T checkNotNull<T>(T reference, {message}) { if (reference == null) { throw ArgumentError(_resolveMessage(message, 'null pointer')); } return reference; } /// Throws a [StateError] if the given [expression] is `false`. void checkState(bool expression, {message}) { if (!expression) { throw StateError(_resolveMessage(message, 'failed precondition')); } } String _resolveMessage(message, String defaultMessage) { if (message is Function) message = message(); if (message == null) return defaultMessage; return message.toString(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/pattern.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// This library contains utilities for working with [RegExp]s and other /// [Pattern]s. library quiver.pattern; // From the PatternCharacter rule here: // http://ecma-international.org/ecma-262/5.1/#sec-15.10 final _specialChars = RegExp(r'([\\\^\$\.\|\+\[\]\(\)\{\}])'); /// Escapes special regex characters in [str] so that it can be used as a /// literal match inside of a [RegExp]. /// /// The special characters are: \ ^ $ . | + [ ] ( ) { } /// as defined here: http://ecma-international.org/ecma-262/5.1/#sec-15.10 String escapeRegex(String str) => str.splitMapJoin(_specialChars, onMatch: (Match m) => '\\${m.group(0)}', onNonMatch: (s) => s); /// Returns a [Pattern] that matches against every pattern in [include] and /// returns all the matches. If the input string matches against any pattern in /// [exclude] no matches are returned. Pattern matchAny(Iterable<Pattern> include, {Iterable<Pattern> exclude}) => _MultiPattern(include, exclude: exclude); class _MultiPattern extends Pattern { _MultiPattern(this.include, {this.exclude}); final Iterable<Pattern> include; final Iterable<Pattern> exclude; @override Iterable<Match> allMatches(String str, [int start = 0]) { final _allMatches = <Match>[]; for (final pattern in include) { var matches = pattern.allMatches(str, start); if (_hasMatch(matches)) { if (exclude != null) { for (final excludePattern in exclude) { if (_hasMatch(excludePattern.allMatches(str, start))) { return []; } } } _allMatches.addAll(matches); } } return _allMatches; } @override Match matchAsPrefix(String str, [int start = 0]) { return allMatches(str) .firstWhere((match) => match.start == start, orElse: () => null); } } /// Returns true if [pattern] has a single match in [str] that matches the /// whole string, not a substring. bool matchesFull(Pattern pattern, String str) { var match = pattern.matchAsPrefix(str); return match != null && match.end == str.length; } bool _hasMatch(Iterable<Match> matches) => matches.iterator.moveNext(); // TODO(justin): add more detailed documentation and explain how matching // differs or is similar to globs in Python and various shells. /// A [Pattern] that matches against filesystem path-like strings with /// wildcards. /// /// The pattern matches strings as follows: /// * The whole string must match, not a substring /// * Any non wildcard is matched as a literal /// * '*' matches one or more characters except '/' /// * '?' matches exactly one character except '/' /// * '**' matches one or more characters including '/' class Glob implements Pattern { Glob(this.pattern) : regex = _regexpFromGlobPattern(pattern); final RegExp regex; final String pattern; @override Iterable<Match> allMatches(String str, [int start = 0]) => regex.allMatches(str, start); @override Match matchAsPrefix(String string, [int start = 0]) => regex.matchAsPrefix(string, start); bool hasMatch(String str) => regex.hasMatch(str); @override String toString() => pattern; @override int get hashCode => pattern.hashCode; @override bool operator ==(other) => other is Glob && pattern == other.pattern; } RegExp _regexpFromGlobPattern(String pattern) { var sb = StringBuffer(); sb.write('^'); var chars = pattern.split(''); for (var i = 0; i < chars.length; i++) { var c = chars[i]; if (_specialChars.hasMatch(c)) { sb.write('\\$c'); } else if (c == '*') { if ((i + 1 < chars.length) && (chars[i + 1] == '*')) { sb.write('.*'); i++; } else { sb.write('[^/]*'); } } else if (c == '?') { sb.write('[^/]'); } else { sb.write(c); } } sb.write(r'$'); return RegExp(sb.toString()); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/cache.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. library quiver.cache; export 'src/cache/cache.dart'; export 'src/cache/map_cache.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/mirrors.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. library quiver.mirrors; import 'dart:mirrors'; /// Returns the qualified name of [t]. @Deprecated('Will be removed in 3.0.0') Symbol getTypeName(Type t) => reflectClass(t).qualifiedName; /// Returns true if [o] implements [type]. @Deprecated('Will be removed in 3.0.0') bool implements(Object o, Type type) => classImplements(reflect(o).type, reflectClass(type)); /// Returns true if the class represented by [classMirror] implements the class /// represented by [interfaceMirror]. @Deprecated('Will be removed in 3.0.0') bool classImplements(ClassMirror classMirror, ClassMirror interfaceMirror) { if (classMirror == null) return false; if (classMirror.qualifiedName == interfaceMirror.qualifiedName) return true; if (classImplements(classMirror.superclass, interfaceMirror)) return true; if (classMirror.superinterfaces .any((i) => classImplements(i, interfaceMirror))) return true; return false; } /// Walks up the class hierarchy to find a method declaration with the given /// [name]. /// /// Note that it's not possible to tell if there's an implementation via /// noSuchMethod(). @Deprecated('Will be removed in 3.0.0') DeclarationMirror getDeclaration(ClassMirror classMirror, Symbol name) { if (classMirror.declarations.containsKey(name)) { return classMirror.declarations[name]; } if (classMirror.superclass != null) { var mirror = getDeclaration(classMirror.superclass, name); if (mirror != null) { return mirror; } } for (final ClassMirror supe in classMirror.superinterfaces) { var mirror = getDeclaration(supe, name); if (mirror != null) { return mirror; } } return null; } /// Closurizes a method reflectively. @Deprecated('Will be removed in 3.0.0') class Method /* implements Function */ { Method(this.mirror, this.symbol); final InstanceMirror mirror; final Symbol symbol; @override dynamic noSuchMethod(Invocation invocation) { if (invocation.isMethod && invocation.memberName == const Symbol('call')) { if (invocation.namedArguments != null && invocation.namedArguments.isNotEmpty) { // this will fail until named argument support is implemented return mirror .invoke(symbol, invocation.positionalArguments, invocation.namedArguments) .reflectee; } return mirror.invoke(symbol, invocation.positionalArguments).reflectee; } return super.noSuchMethod(invocation); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/strings.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. library quiver.strings; /// Returns [true] if [s] is either null, empty or is solely made of whitespace /// characters (as defined by [String.trim]). bool isBlank(String s) => s == null || s.trim().isEmpty; /// Returns [true] if [s] is neither null, empty nor is solely made of whitespace /// characters. /// /// See also: /// /// * [isBlank] bool isNotBlank(String s) => s != null && s.trim().isNotEmpty; /// Returns [true] if [s] is either null or empty. bool isEmpty(String s) => s == null || s.isEmpty; /// Returns [true] if [s] is a not empty string. bool isNotEmpty(String s) => s != null && s.isNotEmpty; /// Returns a string with characters from the given [s] in reverse order. /// /// NOTE: without full support for unicode composed character sequences, /// sequences including zero-width joiners, etc. this function is unsafe to /// use. No replacement is provided. String _reverse(String s) { if (s == null || s == '') return s; StringBuffer sb = StringBuffer(); var runes = s.runes.iterator..reset(s.length); while (runes.movePrevious()) { sb.writeCharCode(runes.current); } return sb.toString(); } /// Loops over [s] and returns traversed characters. Takes arbitrary [from] and /// [to] indices. Works as a substitute for [String.substring], except it never /// throws [RangeError]. Supports negative indices. Think of an index as a /// coordinate in an infinite in both directions vector filled with repeating /// string [s], whose 0-th coordinate coincides with the 0-th character in [s]. /// Then [loop] returns the sub-vector defined by the interval ([from], [to]). /// [from] is inclusive. [to] is exclusive. /// /// This method throws exceptions on [null] and empty strings. /// /// If [to] is omitted or is [null] the traversing ends at the end of the loop. /// /// If [to] < [from], traverses [s] in the opposite direction. /// /// For example: /// /// loop('Hello, World!', 7) == 'World!' /// loop('ab', 0, 6) == 'ababab' /// loop('test.txt', -3) == 'txt' /// loop('ldwor', -3, 2) == 'world' String loop(String s, int from, [int to]) { if (s == null || s == '') { throw ArgumentError('Input string cannot be null or empty'); } if (to != null && to < from) { // TODO(cbracken): throw ArgumentError in this case. return loop(_reverse(s), -from, -to); } int len = s.length; int leftFrag = from >= 0 ? from ~/ len : ((from - len) ~/ len); to ??= (leftFrag + 1) * len; int rightFrag = to - 1 >= 0 ? to ~/ len : ((to - len) ~/ len); int fragOffset = rightFrag - leftFrag - 1; if (fragOffset == -1) { return s.substring(from - leftFrag * len, to - rightFrag * len); } StringBuffer sink = StringBuffer(s.substring(from - leftFrag * len)); _repeat(sink, s, fragOffset); sink.write(s.substring(0, to - rightFrag * len)); return sink.toString(); } void _repeat(StringBuffer sink, String s, int times) { for (int i = 0; i < times; i++) { sink.write(s); } } /// Returns `true` if [rune] represents a digit. /// /// The definition of digit matches the Unicode `0x3?` range of Western /// European digits. bool isDigit(int rune) => rune ^ 0x30 <= 9; /// Returns `true` if [rune] represents a whitespace character. /// /// The definition of whitespace matches that used in [String.trim] which is /// based on Unicode 6.2. This maybe be a different set of characters than the /// environment's [RegExp] definition for whitespace, which is given by the /// ECMAScript standard: http://ecma-international.org/ecma-262/5.1/#sec-15.10 bool isWhitespace(int rune) => (rune >= 0x0009 && rune <= 0x000D) || rune == 0x0020 || rune == 0x0085 || rune == 0x00A0 || rune == 0x1680 || rune == 0x180E || (rune >= 0x2000 && rune <= 0x200A) || rune == 0x2028 || rune == 0x2029 || rune == 0x202F || rune == 0x205F || rune == 0x3000 || rune == 0xFEFF; /// Returns a [String] of length [width] padded with the same number of /// characters on the left and right from [fill]. On the right, characters are /// selected from [fill] starting at the end so that the last character in /// [fill] is the last character in the result. [fill] is repeated if /// neccessary to pad. /// /// Returns [input] if `input.length` is equal to or greater than width. /// [input] can be `null` and is treated as an empty string. /// /// If there are an odd number of characters to pad, then the right will be /// padded with one more than the left. String center(String input, int width, String fill) { if (fill == null || fill.isEmpty) { throw ArgumentError('fill cannot be null or empty'); } input ??= ''; if (input.length >= width) return input; var padding = width - input.length; if (padding ~/ 2 > 0) { input = loop(fill, 0, padding ~/ 2) + input; } return input + loop(fill, input.length - width, 0); } /// Returns `true` if [a] and [b] are equal after being converted to lower /// case, or are both null. bool equalsIgnoreCase(String a, String b) => (a == null && b == null) || (a != null && b != null && a.toLowerCase() == b.toLowerCase()); /// Compares [a] and [b] after converting to lower case. /// /// Both [a] and [b] must not be null. int compareIgnoreCase(String a, String b) => a.toLowerCase().compareTo(b.toLowerCase());
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/io.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. library quiver.io; import 'dart:async'; import 'dart:convert' show Encoding, utf8; import 'dart:io'; import 'src/async/string.dart' as astring; /// Converts a [Stream] of byte lists to a [String]. @Deprecated('Moved to quiver/async.dart. This copy will be removed in 3.0.0') Future<String> byteStreamToString(Stream<List<int>> stream, {Encoding encoding = utf8}) => astring.byteStreamToString(stream, encoding: encoding); /// Gets the full path of [path] by using [File.fullPathSync]. @Deprecated('Use File(path).resolveSymbolicLinksSync. Will be removed in 3.0.0') String getFullPath(path) => File(path).resolveSymbolicLinksSync(); /// Lists the sub-directories and files of this Directory, optionally recursing /// into sub-directories based on the return value of [visit]. /// /// [visit] is called with a [File], [Directory] or [Link] to a directory, /// never a Symlink to a File. If [visit] returns true, then its argument is /// listed recursively. @Deprecated('Will be removed in 3.0.0') Future visitDirectory(Directory dir, Future<bool> visit(FileSystemEntity f)) { final completer = Completer(); final directories = <String, bool>{dir.path: false}; void _list(Directory dir) { directories.putIfAbsent(dir.path, () => false); dir.list(followLinks: false).listen((FileSystemEntity entity) { var future = visit(entity); // TODO(cbracken): Remove this post-NNBD. if (future == null) return; future.then((bool recurse) { // recurse on directories, but not cyclic symlinks if (entity is! File && recurse == true) { if (entity is Link) { if (FileSystemEntity.typeSync(entity.path, followLinks: true) == FileSystemEntityType.directory) { var fullPath = getFullPath(entity.path).toString(); var dirFullPath = getFullPath(dir.path).toString(); if (!dirFullPath.startsWith(fullPath)) { _list(Directory(entity.path)); } } } else if (entity is Directory) { _list(entity); } } }); }, onDone: () { directories[dir.path] = true; if (directories.values.every((v) => v)) { completer.complete(); } }, onError: (e) { completer.completeError(e); }, cancelOnError: true); } _list(dir); return completer.future; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/async.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. library quiver.async; export 'src/async/collect.dart'; export 'src/async/concat.dart'; export 'src/async/countdown_timer.dart'; export 'src/async/enumerate.dart'; export 'src/async/future_stream.dart'; export 'src/async/iteration.dart'; export 'src/async/metronome.dart'; export 'src/async/stream_buffer.dart'; export 'src/async/stream_router.dart'; export 'src/async/string.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/testing/time.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Testing support for dart:core time functionality. library quiver.testing.time; export 'src/time/time.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/testing/equality.dart
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Utilities for testing the equality of Dart object library quiver.testing.equality; export 'src/equality/equality.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/testing/runtime.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Testing support related to the Dart runtime. library quiver.testing.runtime; export 'src/runtime/checked_mode.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/testing/async.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Testing support for dart:async. library quiver.testing.async; export 'src/async/fake_async.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/testing/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/testing/src/time/time.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Returns the current test time in microseconds. typedef Now = int Function(); /// A [Stopwatch] implementation that gets the current time in microseconds /// via a user-supplied function. class FakeStopwatch implements Stopwatch { FakeStopwatch(int now(), this.frequency) : _now = now, _start = null, _stop = null; final Now _now; int _start; int _stop; @override int frequency; @override void start() { if (isRunning) return; if (_start == null) { _start = _now(); } else { _start = _now() - (_stop - _start); _stop = null; } } @override void stop() { if (!isRunning) return; _stop = _now(); } @override void reset() { if (_start == null) return; _start = _now(); if (_stop != null) { _stop = _start; } } @override int get elapsedTicks { if (_start == null) { return 0; } return (_stop == null) ? (_now() - _start) : (_stop - _start); } @override Duration get elapsed => Duration(microseconds: elapsedMicroseconds); @override int get elapsedMicroseconds => (elapsedTicks * 1000000) ~/ frequency; @override int get elapsedMilliseconds => (elapsedTicks * 1000) ~/ frequency; @override bool get isRunning => _start != null && _stop == null; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/testing/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/testing/src/equality/equality.dart
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:matcher/matcher.dart'; /// Matcher for == and hashCode methods of a class. /// /// To use, invoke areEqualityGroups with a list of equality groups where each /// group contains objects that are supposed to be equal to each other, and /// objects of different groups are expected to be unequal. For example: /// /// expect({ /// 'hello': ["hello", "h" + "ello"], /// 'world': ["world", "wor" + "ld"], /// 'three': [2, 1 + 1] /// }, areEqualityGroups); /// /// This tests that: /// /// * comparing each object against itself returns true /// * comparing each object against an instance of an incompatible class /// returns false /// * comparing each pair of objects within the same equality group returns /// true /// * comparing each pair of objects from different equality groups returns /// false /// * the hash codes of any two equal objects are equal /// * equals implementation is idempotent /// /// The format of the Map passed to expect is such that the map keys are used in /// error messages to identify the group described by the map value. /// /// When a test fails, the error message labels the objects involved in /// the failed comparison as follows: /// /// "`[group x, item j]`" refers to the ith item in the xth equality group, /// where both equality groups and the items within equality groups are /// numbered starting from 1. When either a constructor argument or an /// equal object is provided, that becomes group 1. const Matcher areEqualityGroups = _EqualityGroupMatcher(); const _repetitions = 3; class _EqualityGroupMatcher extends Matcher { const _EqualityGroupMatcher(); static const failureReason = 'failureReason'; @override Description describe(Description description) => description.add('to be equality groups'); @override bool matches(item, Map matchState) { try { _verifyEqualityGroups(item, matchState); return true; } on MatchError catch (e) { matchState[failureReason] = e.toString(); return false; } } @override Description describeMismatch(item, Description mismatchDescription, Map matchState, bool verbose) => mismatchDescription.add(' ${matchState[failureReason]}'); void _verifyEqualityGroups(Map<String, List> equalityGroups, Map matchState) { if (equalityGroups == null) { throw MatchError('Equality Group must not be null'); } final equalityGroupsCopy = <String, List>{}; equalityGroups.forEach((String groupName, List group) { if (groupName == null) { throw MatchError('Group name must not be null'); } if (group == null) { throw MatchError('Group must not be null'); } equalityGroupsCopy[groupName] = List.from(group); }); // Run the test multiple times to ensure deterministic equals for (var i = 0; i < _repetitions; i++) { _checkBasicIdentity(equalityGroupsCopy, matchState); _checkGroupBasedEquality(equalityGroupsCopy); } } void _checkBasicIdentity(Map<String, List> equalityGroups, Map matchState) { var flattened = equalityGroups.values.expand((group) => group); for (final item in flattened) { if (item == _NotAnInstance.equalToNothing) { throw MatchError( '$item must not be equal to an arbitrary object of another class'); } if (item != item) { throw MatchError('$item must be equal to itself'); } if (item.hashCode != item.hashCode) { throw MatchError('the implementation of hashCode of $item must ' 'be idempotent'); } } } void _checkGroupBasedEquality(Map<String, List> equalityGroups) { equalityGroups.forEach((String groupName, List group) { var groupLength = group.length; for (var itemNumber = 0; itemNumber < groupLength; itemNumber++) { _checkEqualToOtherGroup( equalityGroups, groupLength, itemNumber, groupName); _checkUnequalToOtherGroups(equalityGroups, groupName, itemNumber); } }); } void _checkUnequalToOtherGroups( Map<String, List> equalityGroups, String groupName, int itemNumber) { equalityGroups.forEach((String unrelatedGroupName, List unrelatedGroup) { if (groupName != unrelatedGroupName) { for (var unrelatedItemNumber = 0; unrelatedItemNumber < unrelatedGroup.length; unrelatedItemNumber++) { _expectUnrelated(equalityGroups, groupName, itemNumber, unrelatedGroupName, unrelatedItemNumber); } } }); } void _checkEqualToOtherGroup(Map<String, List> equalityGroups, int groupLength, int itemNumber, String groupName) { for (var relatedItemNumber = 0; relatedItemNumber < groupLength; relatedItemNumber++) { if (itemNumber != relatedItemNumber) { _expectRelated( equalityGroups, groupName, itemNumber, relatedItemNumber); } } } void _expectRelated(Map<String, List> equalityGroups, String groupName, int itemNumber, int relatedItemNumber) { var itemInfo = _createItem(equalityGroups, groupName, itemNumber); var relatedInfo = _createItem(equalityGroups, groupName, relatedItemNumber); if (itemInfo.value != relatedInfo.value) { throw MatchError('$itemInfo must be equal to $relatedInfo'); } if (itemInfo.value.hashCode != relatedInfo.value.hashCode) { throw MatchError( 'the hashCode (${itemInfo.value.hashCode}) of $itemInfo must ' 'be equal to the hashCode (${relatedInfo.value.hashCode}) of ' '$relatedInfo}'); } } void _expectUnrelated(Map<String, List> equalityGroups, String groupName, int itemNumber, String unrelatedGroupName, int unrelatedItemNumber) { var itemInfo = _createItem(equalityGroups, groupName, itemNumber); var unrelatedInfo = _createItem(equalityGroups, unrelatedGroupName, unrelatedItemNumber); if (itemInfo.value == unrelatedInfo.value) { throw MatchError('$itemInfo must not be equal to $unrelatedInfo)'); } } _Item _createItem( Map<String, List> equalityGroups, String groupName, int itemNumber) => _Item(equalityGroups[groupName][itemNumber], groupName, itemNumber); } class _NotAnInstance { const _NotAnInstance._(); static const equalToNothing = _NotAnInstance._(); } class _Item { _Item(this.value, this.groupName, this.itemNumber); final Object value; final String groupName; final int itemNumber; @override String toString() => "$value [group '$groupName', item ${itemNumber + 1}]"; } class MatchError extends Error { /// The [message] describes the match error. MatchError([this.message]); final String message; @override String toString() => message; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/testing/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/testing/src/runtime/checked_mode.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Asserts that the current runtime has checked mode enabled. /// /// Otherwise, throws [StateError]. @Deprecated('Checked mode is meaningless in Dart 2.0. Will be removed in 3.0.0') void assertCheckedMode() { _isCheckedMode ??= _checkForCheckedMode(); if (!_isCheckedMode) { throw StateError('Not in checked mode.'); } } bool _isCheckedMode; bool _checkForCheckedMode() { Object sentinal = Object(); try { var i = 1 as dynamic; _takeString(i); throw sentinal; } catch (e) { if (e == sentinal) return false; } return true; } void _takeString(String value) {}
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/testing/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/testing/src/async/fake_async.dart
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:async'; import 'dart:collection' show Queue; import 'package:quiver/time.dart'; /// A mechanism to make time-dependent units testable. /// /// Test code can be passed as a callback to [run], which causes it to be run in /// a [Zone] which fakes timer and microtask creation, such that they are run /// during calls to [elapse] which simulates the asynchronous passage of time. /// /// The synchronous passage of time (blocking or expensive calls) can also be /// simulated using [elapseBlocking]. /// /// To allow the unit under test to tell time, it can receive a [Clock] as a /// dependency, and default it to [const Clock()] in production, but then use /// [clock] in test code. /// /// Example: /// /// test('testedFunc', () { /// FakeAsync().run((async) { /// testedFunc(clock: async.getClock(initialTime)); /// async.elapse(duration); /// expect(...) /// }); /// }); abstract class FakeAsync { factory FakeAsync() = _FakeAsync; /// Returns a fake [Clock] whose time can is elapsed by calls to [elapse] and /// [elapseBlocking]. /// /// The returned clock starts at [initialTime], and calls to [elapse] and /// [elapseBlocking] advance the clock, even if they occured before the call /// to this method. /// /// The clock can be passed as a dependency to the unit under test. Clock getClock(DateTime initialTime); /// Simulates the asynchronous passage of time. /// /// **This should only be called from within the zone used by [run].** /// /// If [duration] is negative, the returned future completes with an /// [ArgumentError]. /// /// If a previous call to [elapse] has not yet completed, throws a /// [StateError]. /// /// Any Timers created within the zone used by [run] which are to expire /// at or before the new time after [duration] has elapsed are run. /// The microtask queue is processed surrounding each timer. When a timer is /// run, the [clock] will have been advanced by the timer's specified /// duration. Calls to [elapseBlocking] from within these timers and /// microtasks which cause the [clock] to elapse more than the specified /// [duration], can cause more timers to expire and thus be called. /// /// Once all expired timers are processed, the [clock] is advanced (if /// necessary) to the time this method was called + [duration]. void elapse(Duration duration); /// Simulates the synchronous passage of time, resulting from blocking or /// expensive calls. /// /// Neither timers nor microtasks are run during this call. Upon return, the /// [clock] will have been advanced by [duration]. /// /// If [duration] is negative, throws an [ArgumentError]. void elapseBlocking(Duration duration); /// Runs [callback] in a [Zone] with fake timer and microtask scheduling. /// /// Uses /// [ZoneSpecification.createTimer], [ZoneSpecification.createPeriodicTimer], /// and [ZoneSpecification.scheduleMicrotask] to store callbacks for later /// execution within the zone via calls to [elapse]. /// /// Calls [callback] with `this` as argument and returns the result returned /// by [callback]. dynamic run(callback(FakeAsync self)); /// Runs all remaining microtasks, including those scheduled as a result of /// running them, until there are no more microtasks scheduled. /// /// Does not run timers. void flushMicrotasks(); /// Runs all timers until no timers remain (subject to [flushPeriodicTimers] /// option), including those scheduled as a result of running them. /// /// [timeout] lets you set the maximum amount of time the flushing will take. /// Throws a [StateError] if the [timeout] is exceeded. The default timeout /// is 1 hour. [timeout] is relative to the elapsed time. void flushTimers( {Duration timeout = const Duration(hours: 1), bool flushPeriodicTimers = true}); /// Debugging information for all pending timers. /// /// Each returned [String] will contain details about the [Timer] in its first /// line and will contain the stack trace from its construction on subsequent /// lines. The stack trace can passed to [StackTrace.fromString]. List<String> get pendingTimersDebugInfo; /// The number of created periodic timers that have not been canceled. int get periodicTimerCount; /// The number of pending non periodic timers that have not been canceled. int get nonPeriodicTimerCount; /// The number of pending microtasks. int get microtaskCount; } class _FakeAsync implements FakeAsync { Duration _elapsed = Duration.zero; Duration _elapsingTo; final Queue<Function> _microtasks = Queue(); final Set<_FakeTimer> _timers = Set<_FakeTimer>(); @override Clock getClock(DateTime initialTime) => Clock(() => initialTime.add(_elapsed)); @override void elapse(Duration duration) { if (duration.inMicroseconds < 0) { throw ArgumentError('Cannot call elapse with negative duration'); } if (_elapsingTo != null) { throw StateError('Cannot elapse until previous elapse is complete.'); } _elapsingTo = _elapsed + duration; _drainTimersWhile((_FakeTimer next) => next._nextCall <= _elapsingTo); _elapseTo(_elapsingTo); _elapsingTo = null; } @override void elapseBlocking(Duration duration) { if (duration.inMicroseconds < 0) { throw ArgumentError('Cannot call elapse with negative duration'); } _elapsed += duration; if (_elapsingTo != null && _elapsed > _elapsingTo) { _elapsingTo = _elapsed; } } @override void flushMicrotasks() { _drainMicrotasks(); } @override void flushTimers( {Duration timeout = const Duration(hours: 1), bool flushPeriodicTimers = true}) { final absoluteTimeout = _elapsed + timeout; _drainTimersWhile((_FakeTimer timer) { if (timer._nextCall > absoluteTimeout) { throw StateError('Exceeded timeout $timeout while flushing timers'); } if (flushPeriodicTimers) { return _timers.isNotEmpty; } else { // translation: drain every timer (periodic or not) that will occur up // until the latest non-periodic timer return _timers.any((_FakeTimer timer) => !timer._isPeriodic || timer._nextCall <= _elapsed); } }); } @override List<String> get pendingTimersDebugInfo => _timers.map((timer) => '${timer.debugInfo}').toList(growable: false); @override dynamic run(callback(FakeAsync self)) { _zone ??= Zone.current.fork(specification: _zoneSpec); dynamic result; _zone.runGuarded(() { result = callback(this); }); return result; } Zone _zone; @override int get periodicTimerCount => _timers.where((_FakeTimer timer) => timer._isPeriodic).length; @override int get nonPeriodicTimerCount => _timers.where((_FakeTimer timer) => !timer._isPeriodic).length; @override int get microtaskCount => _microtasks.length; ZoneSpecification get _zoneSpec => ZoneSpecification( createTimer: (_, __, ___, Duration duration, Function callback) { return _createTimer(duration, callback, false); }, createPeriodicTimer: (_, __, ___, Duration duration, Function callback) { return _createTimer(duration, callback, true); }, scheduleMicrotask: (_, __, ___, Function microtask) { _microtasks.add(microtask); }); void _drainTimersWhile(bool predicate(_FakeTimer timer)) { _drainMicrotasks(); _FakeTimer next; while ((next = _getNextTimer()) != null && predicate(next)) { _runTimer(next); _drainMicrotasks(); } } void _elapseTo(Duration to) { if (to > _elapsed) { _elapsed = to; } } Timer _createTimer(Duration duration, Function callback, bool isPeriodic) { var timer = _FakeTimer._(duration, callback, isPeriodic, this); _timers.add(timer); return timer; } _FakeTimer _getNextTimer() { return _timers.isEmpty ? null : _timers.reduce((t1, t2) => t1._nextCall <= t2._nextCall ? t1 : t2); } void _runTimer(_FakeTimer timer) { assert(timer.isActive); _elapseTo(timer._nextCall); if (timer._isPeriodic) { timer._callback(timer); timer._nextCall += timer._duration; } else { _timers.remove(timer); timer._callback(); } } void _drainMicrotasks() { while (_microtasks.isNotEmpty) { _microtasks.removeFirst()(); } } bool _hasTimer(_FakeTimer timer) => _timers.contains(timer); void _cancelTimer(_FakeTimer timer) => _timers.remove(timer); } class _FakeTimer implements Timer { _FakeTimer._(Duration duration, this._callback, this._isPeriodic, this._time) : _duration = duration < _minDuration ? _minDuration : duration, _creationStackTrace = StackTrace.current { _nextCall = _time._elapsed + _duration; } final Duration _duration; final Function _callback; final bool _isPeriodic; final _FakeAsync _time; final StackTrace _creationStackTrace; Duration _nextCall; // TODO(yjbanov): In browser JavaScript, timers can only run every 4 // milliseconds once sufficiently nested: // http://www.w3.org/TR/html5/webappapis.html#timer-nesting-level // Without some sort of delay this can lead to infinitely looping timers. // What do the dart VM and dart2js timers do here? static const _minDuration = Duration.zero; @override bool get isActive => _time._hasTimer(this); @override void cancel() => _time._cancelTimer(this); @override int get tick { // TODO(yjbanov): Dart 2.0 requires this method to be implemented. throw UnimplementedError('tick'); } /// Returns debugging information to try to identify the source of the /// [Timer]. /// /// See [FakeAsync.pendingTimersDebugInfo] for requirements on the format. String get debugInfo => 'Timer (duration: $_duration, periodic: $_isPeriodic), created:\n' '$_creationStackTrace'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/cache/map_cache.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:async'; import 'dart:collection'; import 'package:quiver/collection.dart' show LruMap; import 'cache.dart'; /// A [Cache] that's backed by a [Map]. class MapCache<K, V> implements Cache<K, V> { /// Creates a new [MapCache], optionally using [map] as the backing [Map]. MapCache({Map<K, V> map}) : _map = map ?? HashMap<K, V>(); /// Creates a new [MapCache], using [LruMap] as the backing [Map]. /// Optionally specify [maximumSize]. factory MapCache.lru({int maximumSize}) { return MapCache<K, V>(map: LruMap(maximumSize: maximumSize)); } final Map<K, V> _map; /// Map of outstanding ifAbsent calls used to prevent concurrent loads of the same key. final _outstanding = <K, FutureOr<V>>{}; @override Future<V> get(K key, {Loader<K, V> ifAbsent}) async { if (_map.containsKey(key)) { return _map[key]; } // If this key is already loading then return the existing future. if (_outstanding.containsKey(key)) { return _outstanding[key]; } if (ifAbsent != null) { var futureOr = ifAbsent(key); _outstanding[key] = futureOr; V v; try { v = await futureOr; } finally { // Always remove key from [_outstanding] to prevent returning the // failed result again. _outstanding.remove(key); } _map[key] = v; return v; } return null; } @override Future<Null> set(K key, V value) async { _map[key] = value; } @override Future<Null> invalidate(K key) async { _map.remove(key); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/cache/cache.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:async'; /// A function that produces a value for [key], for when a [Cache] needs to /// populate an entry. /// /// The loader function should either return a value synchronously or a /// [Future] which completes with the value asynchronously. typedef Loader<K, V> = FutureOr<V> Function(K key); /// A semi-persistent mapping of keys to values. /// /// All access to a Cache is asynchronous because many implementations will /// store their entries in remote systems, isolates, or otherwise have to do /// async IO to read and write. abstract class Cache<K, V> { /// Returns the value associated with [key]. Future<V> get(K key, {Loader<K, V> ifAbsent}); /// Sets the value associated with [key]. The Future completes with null when /// the operation is complete. Future<Null> set(K key, V value); /// Removes the value associated with [key]. The Future completes with null /// when the operation is complete. Future<Null> invalidate(K key); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/time/util.dart
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:meta/meta.dart'; /// Days in a month. This array uses 1-based month numbers, i.e. January is /// the 1-st element in the array, not the 0-th. const _daysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; /// Returns the number of days in the specified month. /// /// This function assumes the use of the Gregorian calendar or the proleptic /// Gregorian calendar. int daysInMonth(int year, int month) => (month == DateTime.february && isLeapYear(year)) ? 29 : _daysInMonth[month]; /// Returns true if [year] is a leap year. /// /// This implements the Gregorian calendar leap year rules wherein a year is /// considered to be a leap year if it is divisible by 4, excepting years /// divisible by 100, but including years divisible by 400. /// /// This function assumes the use of the Gregorian calendar or the proleptic /// Gregorian calendar. bool isLeapYear(int year) => (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)); /// Takes a [date] that may be outside the allowed range of dates for a given /// [month] in a given [year] and returns the closest date that is within the /// allowed range. /// /// For example: /// /// February 31, 2013 => February 28, 2013 /// /// When jumping from month to month or from leap year to common year we may /// end up in a month that has fewer days than the month we are jumping from. /// In that case it is impossible to preserve the exact date. So we "clamp" the /// date value to fit within the month. For example, jumping from March 31 one /// month back takes us to February 28 (or 29 during a leap year), as February /// doesn't have 31-st date. int clampDayOfMonth({ @required int year, @required int month, @required int day, }) => day.clamp(1, daysInMonth(year, month));
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/time/clock.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'util.dart'; /// Returns current time. typedef TimeFunction = DateTime Function(); /// Return current system time. DateTime systemTime() => DateTime.now(); /// Provides points in time relative to the current point in time, for example: /// now, 2 days ago, 4 weeks from now, etc. /// /// This class is designed with testability in mind. The current point in time /// (or [now()]) is defined by a [TimeFunction]. By supplying your own time /// function or by using fixed clock (see constructors), you can control /// exactly what time a [Clock] returns and base your test expectations on /// that. See specific constructors for how to supply time functions. class Clock { /// Creates a clock based on the given [timeFunc]. /// /// If [timeFunc] is not provided, creates [Clock] based on system clock. /// /// Custom [timeFunc] can be useful in unit-tests. For example, you might /// want to control what time it is now and set date and time expectations in /// your test cases. const Clock([TimeFunction timeFunc = systemTime]) : _time = timeFunc; /// Creates [Clock] that returns fixed [time] value. Useful in unit-tests. Clock.fixed(DateTime time) : _time = (() => time); final TimeFunction _time; /// Returns current time. DateTime now() => _time(); /// Returns the point in time [Duration] amount of time ago. DateTime agoBy(Duration duration) => now().subtract(duration); /// Returns the point in time [Duration] amount of time from now. DateTime fromNowBy(Duration duration) => now().add(duration); /// Returns the point in time that's given amount of time ago. The /// amount of time is the sum of individual parts. Parts are compatible with /// ones defined in [Duration]. DateTime ago( {int days = 0, int hours = 0, int minutes = 0, int seconds = 0, int milliseconds = 0, int microseconds = 0}) => agoBy(Duration( days: days, hours: hours, minutes: minutes, seconds: seconds, milliseconds: milliseconds, microseconds: microseconds)); /// Returns the point in time that's given amount of time from now. The /// amount of time is the sum of individual parts. Parts are compatible with /// ones defined in [Duration]. DateTime fromNow( {int days = 0, int hours = 0, int minutes = 0, int seconds = 0, int milliseconds = 0, int microseconds = 0}) => fromNowBy(Duration( days: days, hours: hours, minutes: minutes, seconds: seconds, milliseconds: milliseconds, microseconds: microseconds)); /// Return the point in time [micros] microseconds ago. DateTime microsAgo(int micros) => ago(microseconds: micros); /// Return the point in time [micros] microseconds from now. DateTime microsFromNow(int micros) => fromNow(microseconds: micros); /// Return the point in time [millis] milliseconds ago. DateTime millisAgo(int millis) => ago(milliseconds: millis); /// Return the point in time [millis] milliseconds from now. DateTime millisFromNow(int millis) => fromNow(milliseconds: millis); /// Return the point in time [seconds] ago. DateTime secondsAgo(int seconds) => ago(seconds: seconds); /// Return the point in time [seconds] from now. DateTime secondsFromNow(int seconds) => fromNow(seconds: seconds); /// Return the point in time [minutes] ago. DateTime minutesAgo(int minutes) => ago(minutes: minutes); /// Return the point in time [minutes] from now. DateTime minutesFromNow(int minutes) => fromNow(minutes: minutes); /// Return the point in time [hours] ago. DateTime hoursAgo(int hours) => ago(hours: hours); /// Return the point in time [hours] from now. DateTime hoursFromNow(int hours) => fromNow(hours: hours); /// Return the point in time [days] ago. DateTime daysAgo(int days) => ago(days: days); /// Return the point in time [days] from now. DateTime daysFromNow(int days) => fromNow(days: days); /// Return the point in time [weeks] ago. DateTime weeksAgo(int weeks) => ago(days: 7 * weeks); /// Return the point in time [weeks] from now. DateTime weeksFromNow(int weeks) => fromNow(days: 7 * weeks); /// Return the point in time [months] ago on the same date. DateTime monthsAgo(int months) { var time = now(); var m = (time.month - months - 1) % 12 + 1; var y = time.year - (months + 12 - time.month) ~/ 12; var d = clampDayOfMonth(year: y, month: m, day: time.day); return DateTime( y, m, d, time.hour, time.minute, time.second, time.millisecond); } /// Return the point in time [months] from now on the same date. DateTime monthsFromNow(int months) { var time = now(); var m = (time.month + months - 1) % 12 + 1; var y = time.year + (months + time.month - 1) ~/ 12; var d = clampDayOfMonth(year: y, month: m, day: time.day); return DateTime( y, m, d, time.hour, time.minute, time.second, time.millisecond); } /// Return the point in time [years] ago on the same date. DateTime yearsAgo(int years) { var time = now(); var y = time.year - years; var d = clampDayOfMonth(year: y, month: time.month, day: time.day); return DateTime(y, time.month, d, time.hour, time.minute, time.second, time.millisecond); } /// Return the point in time [years] from now on the same date. DateTime yearsFromNow(int years) => yearsAgo(-years); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/time/duration_unit_constants.dart
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. const Duration aMicrosecond = Duration(microseconds: 1); const Duration aMillisecond = Duration(milliseconds: 1); const Duration aSecond = Duration(seconds: 1); const Duration aMinute = Duration(minutes: 1); const Duration anHour = Duration(hours: 1); const Duration aDay = Duration(days: 1); const Duration aWeek = Duration(days: 7);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/core/optional.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:collection'; /// A value that might be absent. /// /// Use Optional as an alternative to allowing fields, parameters or return /// values to be null. It signals that a value is not required and provides /// convenience methods for dealing with the absent case. class Optional<T> extends IterableBase<T> { /// Constructs an empty Optional. const Optional.absent() : _value = null; /// Constructs an Optional of the given [value]. /// /// Throws [ArgumentError] if [value] is null. Optional.of(T value) : _value = value { if (_value == null) throw ArgumentError('Must not be null.'); } /// Constructs an Optional of the given [value]. /// /// If [value] is null, returns [absent()]. const Optional.fromNullable(T value) : _value = value; final T _value; /// True when this optional contains a value. bool get isPresent => _value != null; /// True when this optional contains no value. bool get isNotPresent => _value == null; /// Gets the Optional value. /// /// Throws [StateError] if [value] is null. T get value { if (_value == null) { throw StateError('value called on absent Optional.'); } return _value; } /// Executes a function if the Optional value is present. void ifPresent(void ifPresent(T value)) { if (isPresent) { ifPresent(_value); } } /// Execution a function if the Optional value is absent. void ifAbsent(void ifAbsent()) { if (!isPresent) { ifAbsent(); } } /// Gets the Optional value with a default. /// /// The default is returned if the Optional is [absent()]. /// /// Throws [ArgumentError] if [defaultValue] is null. T or(T defaultValue) { if (defaultValue == null) { throw ArgumentError('defaultValue must not be null.'); } return _value ?? defaultValue; } /// Gets the Optional value, or [null] if there is none. T get orNull => _value; /// Transforms the Optional value. /// /// If the Optional is [absent()], returns [absent()] without applying the transformer. /// /// The transformer must not return [null]. If it does, an [ArgumentError] is thrown. Optional<S> transform<S>(S transformer(T value)) { return _value == null ? Optional<S>.absent() : Optional<S>.of(transformer(_value)); } /// Transforms the Optional value. /// /// If the Optional is [absent()], returns [absent()] without applying the transformer. /// /// Returns [absent()] if the transformer returns [null]. Optional<S> transformNullable<S>(S transformer(T value)) { return _value == null ? Optional<S>.absent() : Optional<S>.fromNullable(transformer(_value)); } @override Iterator<T> get iterator => isPresent ? <T>[_value].iterator : Iterable<T>.empty().iterator; /// Delegates to the underlying [value] hashCode. @override int get hashCode => _value.hashCode; /// Delegates to the underlying [value] operator==. @override bool operator ==(o) => o is Optional<T> && o._value == _value; @override String toString() { return _value == null ? 'Optional { absent }' : 'Optional { value: $_value }'; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/core/hash.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Generates a hash code for multiple [objects]. int hashObjects(Iterable objects) => _finish(objects.fold(0, (h, i) => _combine(h, i.hashCode))); /// Generates a hash code for two objects. int hash2(a, b) => _finish(_combine(_combine(0, a.hashCode), b.hashCode)); /// Generates a hash code for three objects. int hash3(a, b, c) => _finish( _combine(_combine(_combine(0, a.hashCode), b.hashCode), c.hashCode)); /// Generates a hash code for four objects. int hash4(a, b, c, d) => _finish(_combine( _combine(_combine(_combine(0, a.hashCode), b.hashCode), c.hashCode), d.hashCode)); // Jenkins hash functions int _combine(int hash, int value) { hash = 0x1fffffff & (hash + value); hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10)); return hash ^ (hash >> 6); } int _finish(int hash) { hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3)); hash = hash ^ (hash >> 11); return 0x1fffffff & (hash + ((0x00003fff & hash) << 15)); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/collection/multimap.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:math' show Random; /// An associative container that maps a key to multiple values. /// /// Key lookups return mutable collections that are views of the multimap. /// Updates to the multimap are reflected in these collections and similarly, /// modifications to the returned collections are reflected in the multimap. abstract class Multimap<K, V> { /// Constructs a new list-backed multimap. factory Multimap() => ListMultimap<K, V>(); /// Constructs a new list-backed multimap. For each element e of [iterable], /// adds an association from [key](e) to [value](e). [key] and [value] each /// default to the identity function. factory Multimap.fromIterable(Iterable iterable, {K key(element), V value(element)}) = ListMultimap<K, V>.fromIterable; /// Returns whether this multimap contains the given [value]. bool containsValue(Object value); /// Returns whether this multimap contains the given [key]. bool containsKey(Object key); /// Returns whether this multimap contains the given association between [key] /// and [value]. bool contains(Object key, Object value); /// Returns the values for the given [key]. An empty iterable is returned if /// [key] is not mapped. The returned collection is a view on the multimap. /// Updates to the collection modify the multimap and likewise, modifications /// to the multimap are reflected in the returned collection. Iterable<V> operator [](Object key); /// Adds an association from the given key to the given value. void add(K key, V value); /// Adds an association from the given key to each of the given values. void addValues(K key, Iterable<V> values); /// Adds all associations of [other] to this multimap. /// /// The operation is equivalent to doing `this[key] = value` for each key and /// associated value in other. It iterates over [other], which must therefore /// not change during the iteration. void addAll(Multimap<K, V> other); /// Removes the association between the given [key] and [value]. Returns /// `true` if the association existed, `false` otherwise. bool remove(Object key, V value); /// Removes the association for the given [key]. Returns the collection of /// removed values, or an empty iterable if [key] was unmapped. Iterable<V> removeAll(Object key); /// Removes all entries of this multimap that satisfy the given [predicate]. void removeWhere(bool predicate(K key, V value)); /// Removes all data from the multimap. void clear(); /// Applies [f] to each {key, `Iterable<value>`} pair of the multimap. /// /// It is an error to add or remove keys from the map during iteration. void forEachKey(void f(K key, Iterable<V> value)); /// Applies [f] to each {key, value} pair of the multimap. /// /// It is an error to add or remove keys from the map during iteration. void forEach(void f(K key, V value)); /// The keys of [this]. Iterable<K> get keys; /// The values of [this]. Iterable<V> get values; /// Returns a view of this multimap as a map. Map<K, Iterable<V>> asMap(); /// The number of keys in the multimap. int get length; /// Returns true if there is no key in the multimap. bool get isEmpty; /// Returns true if there is at least one key in the multimap. bool get isNotEmpty; } /// Abstract base class for multimap implementations. abstract class _BaseMultimap<K, V, C extends Iterable<V>> implements Multimap<K, V> { _BaseMultimap(); /// Constructs a new multimap. For each element e of [iterable], adds an /// association from [key](e) to [value](e). [key] and [value] each default /// to the identity function. _BaseMultimap.fromIterable(Iterable iterable, {K key(element), V value(element)}) { key ??= _id; value ??= _id; for (final element in iterable) { add(key(element), value(element)); } } static T _id<T>(x) => x; final Map<K, C> _map = {}; C _create(); void _add(C iterable, V value); void _addAll(C iterable, Iterable<V> value); void _clear(C iterable); bool _remove(C iterable, Object value); void _removeWhere(C iterable, K key, bool predicate(K key, V value)); Iterable<V> _wrap(Object key, C iterable); @override bool containsValue(Object value) => values.contains(value); @override bool containsKey(Object key) => _map.keys.contains(key); @override bool contains(Object key, Object value) => _map[key]?.contains(value) == true; @override Iterable<V> operator [](Object key) { return _wrap(key, _map[key] ?? _create()); } @override void add(K key, V value) { _map.putIfAbsent(key, _create); _add(_map[key], value); } @override void addValues(K key, Iterable<V> values) { _map.putIfAbsent(key, _create); _addAll(_map[key], values); } /// Adds all associations of [other] to this multimap. /// /// The operation is equivalent to doing `this[key] = value` for each key and /// associated value in other. It iterates over [other], which must therefore /// not change during the iteration. /// /// This implementation iterates through each key of [other] and adds the /// associated values to this instance via [addValues]. @override void addAll(Multimap<K, V> other) => other.forEachKey(addValues); @override bool remove(Object key, V value) { if (!_map.containsKey(key)) return false; bool removed = _remove(_map[key], value); if (removed && _map[key].isEmpty) _map.remove(key); return removed; } @override Iterable<V> removeAll(Object key) { // Cast to dynamic to remove warnings var values = _map.remove(key) as dynamic; var retValues = _create() as dynamic; if (values != null) { retValues.addAll(values); values.clear(); } return retValues; } @override void removeWhere(bool predicate(K key, V value)) { final emptyKeys = Set<K>(); _map.forEach((K key, Iterable<V> values) { _removeWhere(values, key, predicate); if (_map[key].isEmpty) emptyKeys.add(key); }); emptyKeys.forEach(_map.remove); } @override void clear() { _map.forEach((K key, Iterable<V> value) => _clear(value)); _map.clear(); } @override void forEachKey(void f(K key, C value)) => _map.forEach(f); @override void forEach(void f(K key, V value)) { _map.forEach((K key, Iterable<V> values) { for (final V value in values) { f(key, value); } }); } @override Iterable<K> get keys => _map.keys; @override Iterable<V> get values => _map.values.expand((x) => x); Iterable<Iterable<V>> get _groupedValues => _map.values; @override int get length => _map.length; @override bool get isEmpty => _map.isEmpty; @override bool get isNotEmpty => _map.isNotEmpty; } /// A multimap implementation that uses [List]s to store the values associated /// with each key. class ListMultimap<K, V> extends _BaseMultimap<K, V, List<V>> { ListMultimap(); /// Constructs a new list-backed multimap. For each element e of [iterable], /// adds an association from [key](e) to [value](e). [key] and [value] each /// default to the identity function. ListMultimap.fromIterable(Iterable iterable, {K key(element), V value(element)}) : super.fromIterable(iterable, key: key, value: value); @override List<V> _create() => []; @override void _add(List<V> iterable, V value) { iterable.add(value); } @override void _addAll(List<V> iterable, Iterable<V> value) => iterable.addAll(value); @override void _clear(List<V> iterable) => iterable.clear(); @override bool _remove(List<V> iterable, Object value) => iterable.remove(value); @override void _removeWhere(List<V> iterable, K key, bool predicate(K key, V value)) => iterable.removeWhere((value) => predicate(key, value)); @override List<V> _wrap(Object key, List<V> iterable) => _WrappedList(_map, key, iterable); @override List<V> operator [](Object key) => super[key]; @override List<V> removeAll(Object key) => super.removeAll(key); @override Map<K, List<V>> asMap() => _WrappedMap<K, V, List<V>>(this); } /// A multimap implementation that uses [Set]s to store the values associated /// with each key. class SetMultimap<K, V> extends _BaseMultimap<K, V, Set<V>> { SetMultimap(); /// Constructs a new set-backed multimap. For each element e of [iterable], /// adds an association from [key](e) to [value](e). [key] and [value] each /// default to the identity function. SetMultimap.fromIterable(Iterable iterable, {K key(element), V value(element)}) : super.fromIterable(iterable, key: key, value: value); @override Set<V> _create() => Set<V>(); @override void _add(Set<V> iterable, V value) { iterable.add(value); } @override void _addAll(Set<V> iterable, Iterable<V> value) => iterable.addAll(value); @override void _clear(Set<V> iterable) => iterable.clear(); @override bool _remove(Set<V> iterable, Object value) => iterable.remove(value); @override void _removeWhere(Set<V> iterable, K key, bool predicate(K key, V value)) => iterable.removeWhere((value) => predicate(key, value)); @override Set<V> _wrap(Object key, Iterable<V> iterable) => _WrappedSet(_map, key, iterable); @override Set<V> operator [](Object key) => super[key]; @override Set<V> removeAll(Object key) => super.removeAll(key); @override Map<K, Set<V>> asMap() => _WrappedMap<K, V, Set<V>>(this); } /// A [Map] that delegates its operations to an underlying multimap. class _WrappedMap<K, V, C extends Iterable<V>> implements Map<K, C> { _WrappedMap(this._multimap); final _BaseMultimap<K, V, C> _multimap; @override C operator [](Object key) => _multimap[key]; @override void operator []=(K key, C value) { throw UnsupportedError('Insert unsupported on map view'); } @override void addAll(Map<K, C> other) { throw UnsupportedError('Insert unsupported on map view'); } @override C putIfAbsent(K key, C ifAbsent()) { throw UnsupportedError('Insert unsupported on map view'); } @override void clear() => _multimap.clear(); @override bool containsKey(Object key) => _multimap.containsKey(key); @override bool containsValue(Object value) => _multimap.containsValue(value); @override void forEach(void f(K key, C value)) => _multimap.forEachKey(f); @override bool get isEmpty => _multimap.isEmpty; @override bool get isNotEmpty => _multimap.isNotEmpty; @override Iterable<K> get keys => _multimap.keys; @override int get length => _multimap.length; @override C remove(Object key) => _multimap.removeAll(key); @override Iterable<C> get values => _multimap._groupedValues; @override Map<K2, V2> cast<K2, V2>() { // TODO(cbracken): Dart 2.0 requires this method to be implemented. throw UnimplementedError('cast'); } @override Iterable<MapEntry<K, C>> get entries => _multimap._map.entries; @override void addEntries(Iterable<MapEntry<K, C>> entries) { throw UnsupportedError('Insert unsupported on map view'); } @override Map<K2, C2> map<K2, C2>(MapEntry<K2, C2> transform(K key, C value)) => _multimap._map.map(transform); @override C update(K key, C update(C value), {C ifAbsent()}) { throw UnsupportedError('Update unsupported on map view'); } @override void updateAll(C update(K key, C value)) { throw UnsupportedError('Update unsupported on map view'); } @override void removeWhere(bool test(K key, C value)) { var keysToRemove = <K>[]; for (final key in keys) { if (test(key, this[key])) keysToRemove.add(key); } keysToRemove.forEach(_multimap.removeAll); } } /// Iterable wrapper that syncs to an underlying map. class _WrappedIterable<K, V, C extends Iterable<V>> implements Iterable<V> { _WrappedIterable(this._map, this._key, this._delegate); final K _key; final Map<K, C> _map; C _delegate; void _addToMap() => _map[_key] = _delegate; /// Ensures we hold an up-to-date delegate. In the case where all mappings /// for _key are removed from the multimap, the Iterable referenced by /// _delegate is removed from the underlying map. At that point, any new /// addition via the multimap triggers the creation of a new Iterable, and /// the empty delegate we hold would be stale. As such, we check the /// underlying map and update our delegate when the one we hold is empty. void _syncDelegate() { if (_delegate.isEmpty) { var updated = _map[_key]; if (updated != null) { _delegate = updated; } } } @override bool any(bool test(V element)) { _syncDelegate(); return _delegate.any(test); } @override Iterable<T> cast<T>() { // TODO(cbracken): Dart 2.0 requires this method to be implemented. throw UnimplementedError('cast'); } @override bool contains(Object element) { _syncDelegate(); return _delegate.contains(element); } @override V elementAt(int index) { _syncDelegate(); return _delegate.elementAt(index); } @override bool every(bool test(V element)) { _syncDelegate(); return _delegate.every(test); } @override Iterable<T> expand<T>(Iterable<T> f(V element)) { _syncDelegate(); return _delegate.expand(f); } @override V get first { _syncDelegate(); return _delegate.first; } @override V firstWhere(bool test(V element), {V orElse()}) { _syncDelegate(); return _delegate.firstWhere(test, orElse: orElse); } @override T fold<T>(T initialValue, T combine(T previousValue, V element)) { _syncDelegate(); return _delegate.fold(initialValue, combine); } @override Iterable<V> followedBy(Iterable<V> other) { _syncDelegate(); return _delegate.followedBy(other); } @override void forEach(void f(V element)) { _syncDelegate(); _delegate.forEach(f); } @override bool get isEmpty { _syncDelegate(); return _delegate.isEmpty; } @override bool get isNotEmpty { _syncDelegate(); return _delegate.isNotEmpty; } @override Iterator<V> get iterator { _syncDelegate(); return _delegate.iterator; } @override String join([String separator = '']) { _syncDelegate(); return _delegate.join(separator); } @override V get last { _syncDelegate(); return _delegate.last; } @override V lastWhere(bool test(V element), {V orElse()}) { _syncDelegate(); return _delegate.lastWhere(test, orElse: orElse); } @override int get length { _syncDelegate(); return _delegate.length; } @override Iterable<T> map<T>(T f(V element)) { _syncDelegate(); return _delegate.map(f); } @override V reduce(V combine(V value, V element)) { _syncDelegate(); return _delegate.reduce(combine); } @override V get single { _syncDelegate(); return _delegate.single; } @override V singleWhere(bool test(V element), {V orElse()}) { _syncDelegate(); return _delegate.singleWhere(test, orElse: orElse); } @override Iterable<V> skip(int n) { _syncDelegate(); return _delegate.skip(n); } @override Iterable<V> skipWhile(bool test(V value)) { _syncDelegate(); return _delegate.skipWhile(test); } @override Iterable<V> take(int n) { _syncDelegate(); return _delegate.take(n); } @override Iterable<V> takeWhile(bool test(V value)) { _syncDelegate(); return _delegate.takeWhile(test); } @override List<V> toList({bool growable = true}) { _syncDelegate(); return _delegate.toList(growable: growable); } @override Set<V> toSet() { _syncDelegate(); return _delegate.toSet(); } @override String toString() { _syncDelegate(); return _delegate.toString(); } @override Iterable<V> where(bool test(V element)) { _syncDelegate(); return _delegate.where(test); } @override Iterable<T> whereType<T>() { // TODO(cbracken): Dart 2.0 requires this method to be implemented. throw UnimplementedError('whereType'); } } class _WrappedList<K, V> extends _WrappedIterable<K, V, List<V>> implements List<V> { _WrappedList(Map<K, Iterable<V>> map, K key, List<V> delegate) : super(map, key, delegate); @override V operator [](int index) => elementAt(index); @override void operator []=(int index, V value) { _syncDelegate(); _delegate[index] = value; } @override List<V> operator +(List<V> other) { _syncDelegate(); return _delegate + other; } @override void add(V value) { _syncDelegate(); var wasEmpty = _delegate.isEmpty; _delegate.add(value); if (wasEmpty) _addToMap(); } @override void addAll(Iterable<V> iterable) { _syncDelegate(); var wasEmpty = _delegate.isEmpty; _delegate.addAll(iterable); if (wasEmpty) _addToMap(); } @override Map<int, V> asMap() { _syncDelegate(); return _delegate.asMap(); } @override List<T> cast<T>() { // TODO(cbracken): Dart 2.0 requires this method to be implemented. throw UnimplementedError('cast'); } @override void clear() { _syncDelegate(); _delegate.clear(); _map.remove(_key); } @override void fillRange(int start, int end, [V fillValue]) { _syncDelegate(); _delegate.fillRange(start, end, fillValue); } @override set first(V value) { if (isEmpty) throw RangeError.index(0, this); this[0] = value; } @override Iterable<V> getRange(int start, int end) { _syncDelegate(); return _delegate.getRange(start, end); } @override int indexOf(V element, [int start = 0]) { _syncDelegate(); return _delegate.indexOf(element, start); } @override int indexWhere(bool test(V element), [int start = 0]) { _syncDelegate(); return _delegate.indexWhere(test, start); } @override void insert(int index, V element) { _syncDelegate(); var wasEmpty = _delegate.isEmpty; _delegate.insert(index, element); if (wasEmpty) _addToMap(); } @override void insertAll(int index, Iterable<V> iterable) { _syncDelegate(); var wasEmpty = _delegate.isEmpty; _delegate.insertAll(index, iterable); if (wasEmpty) _addToMap(); } @override set last(V value) { if (isEmpty) throw RangeError.index(0, this); this[length - 1] = value; } @override int lastIndexOf(V element, [int start]) { _syncDelegate(); return _delegate.lastIndexOf(element, start); } @override int lastIndexWhere(bool test(V element), [int start]) { _syncDelegate(); return _delegate.lastIndexWhere(test, start); } @override set length(int newLength) { _syncDelegate(); var wasEmpty = _delegate.isEmpty; _delegate.length = newLength; if (wasEmpty) _addToMap(); } @override bool remove(Object value) { _syncDelegate(); bool removed = _delegate.remove(value); if (_delegate.isEmpty) _map.remove(_key); return removed; } @override V removeAt(int index) { _syncDelegate(); V removed = _delegate.removeAt(index); if (_delegate.isEmpty) _map.remove(_key); return removed; } @override V removeLast() { _syncDelegate(); V removed = _delegate.removeLast(); if (_delegate.isEmpty) _map.remove(_key); return removed; } @override void removeRange(int start, int end) { _syncDelegate(); _delegate.removeRange(start, end); if (_delegate.isEmpty) _map.remove(_key); } @override void removeWhere(bool test(V element)) { _syncDelegate(); _delegate.removeWhere(test); if (_delegate.isEmpty) _map.remove(_key); } @override void replaceRange(int start, int end, Iterable<V> iterable) { _syncDelegate(); _delegate.replaceRange(start, end, iterable); if (_delegate.isEmpty) _map.remove(_key); } @override void retainWhere(bool test(V element)) { _syncDelegate(); _delegate.retainWhere(test); if (_delegate.isEmpty) _map.remove(_key); } @override Iterable<V> get reversed { _syncDelegate(); return _delegate.reversed; } @override void setAll(int index, Iterable<V> iterable) { _syncDelegate(); _delegate.setAll(index, iterable); } @override void setRange(int start, int end, Iterable<V> iterable, [int skipCount = 0]) { _syncDelegate(); } @override void shuffle([Random random]) { _syncDelegate(); _delegate.shuffle(random); } @override void sort([int compare(V a, V b)]) { _syncDelegate(); _delegate.sort(compare); } @override List<V> sublist(int start, [int end]) { _syncDelegate(); return _delegate.sublist(start, end); } } class _WrappedSet<K, V> extends _WrappedIterable<K, V, Set<V>> implements Set<V> { _WrappedSet(Map<K, Iterable<V>> map, K key, Iterable<V> delegate) : super(map, key, delegate); @override bool add(V value) { _syncDelegate(); var wasEmpty = _delegate.isEmpty; bool wasAdded = _delegate.add(value); if (wasEmpty) _addToMap(); return wasAdded; } @override void addAll(Iterable<V> elements) { _syncDelegate(); var wasEmpty = _delegate.isEmpty; _delegate.addAll(elements); if (wasEmpty) _addToMap(); } @override Set<T> cast<T>() { // TODO(cbracken): Dart 2.0 requires this method to be implemented. throw UnimplementedError('cast'); } @override void clear() { _syncDelegate(); _delegate.clear(); _map.remove(_key); } @override bool containsAll(Iterable<Object> other) { _syncDelegate(); return _delegate.containsAll(other); } @override Set<V> difference(Set<Object> other) { _syncDelegate(); return _delegate.difference(other); } @override Set<V> intersection(Set<Object> other) { _syncDelegate(); return _delegate.intersection(other); } @override V lookup(Object object) { _syncDelegate(); return _delegate.lookup(object); } @override bool remove(Object value) { _syncDelegate(); bool removed = _delegate.remove(value); if (_delegate.isEmpty) _map.remove(_key); return removed; } @override void removeAll(Iterable<Object> elements) { _syncDelegate(); _delegate.removeAll(elements); if (_delegate.isEmpty) _map.remove(_key); } @override void removeWhere(bool test(V element)) { _syncDelegate(); _delegate.removeWhere(test); if (_delegate.isEmpty) _map.remove(_key); } @override void retainAll(Iterable<Object> elements) { _syncDelegate(); _delegate.retainAll(elements); if (_delegate.isEmpty) _map.remove(_key); } @override void retainWhere(bool test(V element)) { _syncDelegate(); _delegate.retainWhere(test); if (_delegate.isEmpty) _map.remove(_key); } @override Set<V> union(Set<V> other) { _syncDelegate(); return _delegate.union(other); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/collection/lru_map.dart
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:collection'; import 'package:quiver/iterables.dart' show GeneratingIterable; /// An implementation of a [Map] which has a maximum size and uses a [Least /// Recently Used](http://en.wikipedia.org/wiki/Cache_algorithms#LRU) algorithm /// to remove items from the [Map] when the [maximumSize] is reached and new /// items are added. /// /// It is safe to access the [keys] and [values] collections without affecting /// the "used" ordering - as well as using [forEach]. Other types of access, /// including bracket, and [putIfAbsent], promotes the key-value pair to the /// MRU position. abstract class LruMap<K, V> implements Map<K, V> { /// Creates a [LruMap] instance with the default implementation. factory LruMap({int maximumSize}) = LinkedLruHashMap<K, V>; /// Maximum size of the [Map]. If [length] exceeds this value at any time, n /// entries accessed the earliest are removed, where n is [length] - /// [maximumSize]. int maximumSize; } /// Simple implementation of a linked-list entry that contains a [key] and /// [value]. class _LinkedEntry<K, V> { _LinkedEntry([this.key, this.value]); K key; V value; _LinkedEntry<K, V> next; _LinkedEntry<K, V> previous; } /// A linked hash-table based implementation of [LruMap]. class LinkedLruHashMap<K, V> implements LruMap<K, V> { /// Create a new LinkedLruHashMap with a [maximumSize]. factory LinkedLruHashMap({int maximumSize}) => LinkedLruHashMap._fromMap(HashMap<K, _LinkedEntry<K, V>>(), maximumSize: maximumSize); LinkedLruHashMap._fromMap(this._entries, {int maximumSize}) // This pattern is used instead of a default value because we want to // be able to respect null values coming in from MapCache.lru. : _maximumSize = maximumSize ?? _DEFAULT_MAXIMUM_SIZE; static const _DEFAULT_MAXIMUM_SIZE = 100; final Map<K, _LinkedEntry<K, V>> _entries; int _maximumSize; _LinkedEntry<K, V> _head; _LinkedEntry<K, V> _tail; /// Adds all key-value pairs of [other] to this map. /// /// The operation is equivalent to doing `this[key] = value` for each key and /// associated value in [other]. It iterates over [other], which must /// therefore not change during the iteration. /// /// If a key of [other] is already in this map, its value is overwritten. If /// the number of unique keys is greater than [maximumSize] then the least /// recently use keys are evicted. For keys written to by [other], the least /// recently user order is determined by [other]'s iteration order. @override void addAll(Map<K, V> other) => other.forEach((k, v) => this[k] = v); @override void addEntries(Iterable<MapEntry<K, V>> entries) { for (final entry in entries) { this[entry.key] = entry.value; } } @override LinkedLruHashMap<K2, V2> cast<K2, V2>() { // TODO(cbracken): Dart 2.0 requires this method to be implemented. throw UnimplementedError('cast'); } @override void clear() { _entries.clear(); _head = _tail = null; } @override bool containsKey(Object key) => _entries.containsKey(key); @override bool containsValue(Object value) => values.contains(value); @override Iterable<MapEntry<K, V>> get entries => _entries.values.map((entry) => MapEntry<K, V>(entry.key, entry.value)); /// Applies [action] to each key-value pair of the map in order of MRU to /// LRU. /// /// Calling `action` must not add or remove keys from the map. @override void forEach(void action(K key, V value)) { var head = _head; while (head != null) { action(head.key, head.value); head = head.next; } } @override int get length => _entries.length; @override bool get isEmpty => _entries.isEmpty; @override bool get isNotEmpty => _entries.isNotEmpty; /// Creates an [Iterable] around the entries of the map. Iterable<_LinkedEntry<K, V>> _iterable() { return GeneratingIterable<_LinkedEntry<K, V>>(() => _head, (n) => n.next); } /// The keys of [this] - in order of MRU to LRU. /// /// The returned iterable does *not* have efficient `length` or `contains`. @override Iterable<K> get keys => _iterable().map((e) => e.key); /// The values of [this] - in order of MRU to LRU. /// /// The returned iterable does *not* have efficient `length` or `contains`. @override Iterable<V> get values => _iterable().map((e) => e.value); @override Map<K2, V2> map<K2, V2>(Object transform(K key, V value)) { // TODO(cbracken): Dart 2.0 requires this method to be implemented. // Change Object to MapEntry<K2, V2> when // the MapEntry class has been added. throw UnimplementedError('map'); } @override int get maximumSize => _maximumSize; @override set maximumSize(int maximumSize) { if (maximumSize == null) throw ArgumentError.notNull('maximumSize'); while (length > maximumSize) { _removeLru(); } _maximumSize = maximumSize; } /// Look up the value associated with [key], or add a new value if it isn't /// there. The pair is promoted to the MRU position. /// /// Otherwise calls [ifAbsent] to get a new value, associates [key] to that /// [value], and then returns the new [value], with the key-value pair in the /// MRU position. If this causes [length] to exceed [maximumSize], then the /// LRU position is removed. @override V putIfAbsent(K key, V ifAbsent()) { final entry = _entries.putIfAbsent(key, () => _createEntry(key, ifAbsent())); if (length > maximumSize) { _removeLru(); } _promoteEntry(entry); return entry.value; } /// Get the value for a [key] in the [Map]. /// The [key] will be promoted to the 'Most Recently Used' position. /// /// *NOTE*: Calling `[]` inside an iteration over keys/values is currently /// unsupported; use [keys] or [values] if you need information about entries /// without modifying their position. @override V operator [](Object key) { final entry = _entries[key]; if (entry != null) { _promoteEntry(entry); return entry.value; } else { return null; } } /// If [key] already exists, promotes it to the MRU position & assigns /// [value]. /// /// Otherwise, adds [key] and [value] to the MRU position. If [length] /// exceeds [maximumSize] while adding, removes the LRU position. @override void operator []=(K key, V value) { // Add this item to the MRU position. _insertMru(_createEntry(key, value)); // Remove the LRU item if the size would be exceeded by adding this item. if (length > maximumSize) { assert(length == maximumSize + 1); _removeLru(); } } @override V remove(Object key) { final entry = _entries.remove(key); if (entry != null) { if (entry == _head && entry == _tail) { _head = _tail = null; } else if (entry == _head) { _head = _head.next; _head?.previous = null; } else if (entry == _tail) { _tail = _tail.previous; _tail?.next = null; } else { entry.previous.next = entry.next; entry.next.previous = entry.previous; } return entry.value; } return null; } @override void removeWhere(bool test(K key, V value)) { var keysToRemove = <K>[]; _entries.forEach((key, entry) { if (test(key, entry.value)) keysToRemove.add(key); }); keysToRemove.forEach(remove); } @override // TODO(cbracken): Use the `MapBase.mapToString()` static method when the // minimum SDK version of this package has been bumped to 2.0.0 or greater. String toString() { // Detect toString() cycles. if (_isToStringVisiting(this)) { return '{...}'; } var result = StringBuffer(); try { _toStringVisiting.add(this); result.write('{'); bool first = true; forEach((k, v) { if (!first) { result.write(', '); } first = false; result.write('$k: $v'); }); result.write('}'); } finally { assert(identical(_toStringVisiting.last, this)); _toStringVisiting.removeLast(); } return result.toString(); } @override V update(K key, V update(V value), {V ifAbsent()}) { V newValue; if (containsKey(key)) { newValue = update(this[key]); } else { if (ifAbsent == null) { throw ArgumentError.value(key, 'key', 'Key not in map'); } newValue = ifAbsent(); } // Add this item to the MRU position. _insertMru(_createEntry(key, newValue)); // Remove the LRU item if the size would be exceeded by adding this item. if (length > maximumSize) { assert(length == maximumSize + 1); _removeLru(); } return newValue; } @override void updateAll(V update(K key, V value)) { _entries.forEach((key, entry) { var newValue = _createEntry(key, update(key, entry.value)); _entries[key] = newValue; }); } /// Moves [entry] to the MRU position, shifting the linked list if necessary. void _promoteEntry(_LinkedEntry<K, V> entry) { // If this entry is already in the MRU position we are done. if (entry == _head) { return; } if (entry.previous != null) { // If already existed in the map, link previous to next. entry.previous.next = entry.next; // If this was the tail element, assign a new tail. if (_tail == entry) { _tail = entry.previous; } } // If this entry is not the end of the list then link the next entry to the previous entry. if (entry.next != null) { entry.next.previous = entry.previous; } // Replace head with this element. if (_head != null) { _head.previous = entry; } entry.previous = null; entry.next = _head; _head = entry; // Add a tail if this is the first element. if (_tail == null) { assert(length == 1); _tail = _head; } } /// Creates and returns an entry from [key] and [value]. _LinkedEntry<K, V> _createEntry(K key, V value) { return _LinkedEntry<K, V>(key, value); } /// If [entry] does not exist, inserts it into the backing map. If it does, /// replaces the existing [_LinkedEntry.value] with [entry.value]. Then, in /// either case, promotes [entry] to the MRU position. void _insertMru(_LinkedEntry<K, V> entry) { // Insert a new entry if necessary (only 1 hash lookup in entire function). // Otherwise, just updates the existing value. final value = entry.value; _promoteEntry(_entries.putIfAbsent(entry.key, () => entry)..value = value); } /// Removes the LRU position, shifting the linked list if necessary. void _removeLru() { // Remove the tail from the internal map. _entries.remove(_tail.key); // Remove the tail element itself. _tail = _tail.previous; _tail?.next = null; // If we removed the last element, clear the head too. if (_tail == null) { _head = null; } } } /// A collection used to identify cyclic maps during toString() calls. final List _toStringVisiting = []; /// Check if we are currently visiting `o` in a toString() call. bool _isToStringVisiting(o) => _toStringVisiting.any((e) => identical(o, e));
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/collection/treeset.dart
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:collection'; import 'package:meta/meta.dart' show visibleForTesting; /// A [Set] of items stored in a binary tree according to [comparator]. /// Supports bidirectional iteration. abstract class TreeSet<V> extends IterableBase<V> implements Set<V> { /// Create a new [TreeSet] with an ordering defined by [comparator] or the /// default `(a, b) => a.compareTo(b)`. factory TreeSet({Comparator<V> comparator}) { comparator ??= (a, b) => (a as dynamic).compareTo(b); return AvlTreeSet(comparator: comparator); } TreeSet._(this.comparator); final Comparator<V> comparator; @override int get length; @override bool get isEmpty => length == 0; @override bool get isNotEmpty => length != 0; /// Returns an [BidirectionalIterator] that iterates over this tree. @override BidirectionalIterator<V> get iterator; /// Returns an [BidirectionalIterator] that iterates over this tree, in /// reverse. BidirectionalIterator<V> get reverseIterator; /// Returns an [BidirectionalIterator] that starts at [anchor]. By default, /// the iterator includes the anchor with the first movement; set [inclusive] /// to false if you want to exclude the anchor. Set [reversed] to true to /// change the direction of of moveNext and movePrevious. /// /// Note: This iterator allows you to walk the entire set. It does not /// present a subview. BidirectionalIterator<V> fromIterator(V anchor, {bool reversed = false, bool inclusive = true}); /// Search the tree for the matching [object] or the [nearestOption] /// if missing. See [TreeSearch]. V nearest(V object, {TreeSearch nearestOption = TreeSearch.NEAREST}); @override Set<T> cast<T>(); // TODO(codefu): toString or not toString, that is the question. } /// Controls the results for [TreeSet.searchNearest]() enum TreeSearch { /// If result not found, always chose the smaller element LESS_THAN, /// If result not found, chose the nearest based on comparison NEAREST, /// If result not found, always chose the greater element GREATER_THAN } /// A node in the [TreeSet]. abstract class _TreeNode<V> { /// TreeNodes are always allocated as leafs. _TreeNode({this.object}); _TreeNode<V> get left; _TreeNode<V> get right; // TODO(codefu): Remove need for [parent]; this is just an implementation // note. _TreeNode<V> get parent; V object; /// Return the minimum node for the subtree _TreeNode<V> get minimumNode { var node = this; while (node.left != null) { node = node.left; } return node; } /// Return the maximum node for the subtree _TreeNode<V> get maximumNode { var node = this; while (node.right != null) { node = node.right; } return node; } /// Return the next greatest element (or null) _TreeNode<V> get successor { var node = this; if (node.right != null) { return node.right.minimumNode; } while (node.parent != null && node == node.parent.right) { node = node.parent; } return node.parent; } /// Return the next smaller element (or null) _TreeNode<V> get predecessor { var node = this; if (node.left != null) { return node.left.maximumNode; } while (node.parent != null && node.parent.left == node) { node = node.parent; } return node.parent; } } /// AVL implementation of a self-balancing binary tree. Optimized for lookup /// operations. /// /// Notes: Adapted from "Introduction to Algorithms", second edition, /// by Thomas H. Cormen, Charles E. Leiserson, /// Ronald L. Rivest, Clifford Stein. /// chapter 13.2 class AvlTreeSet<V> extends TreeSet<V> { AvlTreeSet({Comparator<V> comparator}) : super._(comparator); int _length = 0; AvlNode<V> _root; // Modification count to the tree, monotonically increasing int _modCount = 0; @override int get length => _length; /// Add the element to the tree. @override bool add(V element) { if (_root == null) { AvlNode<V> node = AvlNode<V>(object: element); _root = node; ++_length; ++_modCount; return true; } AvlNode<V> x = _root; while (true) { int compare = comparator(element, x.object); if (compare == 0) { return false; } else if (compare < 0) { if (x._left == null) { AvlNode<V> node = AvlNode<V>(object: element).._parent = x; x .._left = node .._balanceFactor -= 1; break; } x = x.left; } else { if (x._right == null) { AvlNode<V> node = AvlNode<V>(object: element).._parent = x; x .._right = node .._balanceFactor += 1; break; } x = x.right; } } ++_modCount; // AVL balancing act (for height balanced trees) // Now that we've inserted, we've unbalanced some trees, we need // to follow the tree back up to the _root double checking that the tree // is still balanced and _maybe_ perform a single or double rotation. // Note: Left additions == -1, Right additions == +1 // Balanced Node = { -1, 0, 1 }, out of balance = { -2, 2 } // Single rotation when Parent & Child share signed balance, // Double rotation when sign differs! AvlNode<V> node = x; while (node._balanceFactor != 0 && node.parent != null) { // Find out which side of the parent we're on if (node.parent._left == node) { node.parent._balanceFactor -= 1; } else { node.parent._balanceFactor += 1; } node = node.parent; if (node._balanceFactor == 2) { // Heavy on the right side - Test for which rotation to perform if (node.right._balanceFactor == 1) { // Single (left) rotation; this will balance everything to zero _rotateLeft(node); node._balanceFactor = node.parent._balanceFactor = 0; node = node.parent; } else { // Double (Right/Left) rotation // node will now be old node.right.left _rotateRightLeft(node); node = node.parent; // Update to new parent (old grandchild) if (node._balanceFactor == 1) { node.right._balanceFactor = 0; node.left._balanceFactor = -1; } else if (node._balanceFactor == 0) { node.right._balanceFactor = 0; node.left._balanceFactor = 0; } else { node.right._balanceFactor = 1; node.left._balanceFactor = 0; } node._balanceFactor = 0; } break; // out of loop, we're balanced } else if (node._balanceFactor == -2) { // Heavy on the left side - Test for which rotation to perform if (node.left._balanceFactor == -1) { _rotateRight(node); node._balanceFactor = node.parent._balanceFactor = 0; node = node.parent; } else { // Double (Left/Right) rotation // node will now be old node.left.right _rotateLeftRight(node); node = node.parent; if (node._balanceFactor == -1) { node.right._balanceFactor = 1; node.left._balanceFactor = 0; } else if (node._balanceFactor == 0) { node.right._balanceFactor = 0; node.left._balanceFactor = 0; } else { node.right._balanceFactor = 0; node.left._balanceFactor = -1; } node._balanceFactor = 0; } break; // out of loop, we're balanced } } // end of while (balancing) _length++; return true; } /// Test to see if an element is stored in the tree AvlNode<V> _getNode(V element) { if (element == null) return null; AvlNode<V> x = _root; while (x != null) { int compare = comparator(element, x.object); if (compare == 0) { // This only means our node matches; we need to search for the exact // element. We could have been glutons and used a hashmap to back. return x; } else if (compare < 0) { x = x.left; } else { x = x.right; } } return null; } /// This function will right rotate/pivot N with its left child, placing /// it on the right of its left child. /// /// N Y /// / \ / \ /// Y A Z N /// / \ ==> / \ / \ /// Z B D CB A /// / \ /// D C /// /// Assertion: must have a left element void _rotateRight(AvlNode<V> node) { AvlNode<V> y = node.left; if (y == null) throw AssertionError(); // turn Y's right subtree(B) into N's left subtree. node._left = y.right; if (node.left != null) { node.left._parent = node; } y._parent = node.parent; if (y._parent == null) { _root = y; } else { if (node.parent._left == node) { node.parent._left = y; } else { node.parent._right = y; } } y._right = node; node._parent = y; } /// This function will left rotate/pivot N with its right child, placing /// it on the left of its right child. /// /// N Y /// / \ / \ /// A Y N Z /// / \ ==> / \ / \ /// B Z A BC D /// / \ /// C D /// /// Assertion: must have a right element void _rotateLeft(AvlNode<V> node) { AvlNode<V> y = node.right; if (y == null) throw AssertionError(); // turn Y's left subtree(B) into N's right subtree. node._right = y.left; if (node.right != null) { node.right._parent = node; } y._parent = node.parent; if (y._parent == null) { _root = y; } else { if (node.parent._left == node) { y.parent._left = y; } else { y.parent._right = y; } } y._left = node; node._parent = y; } /// This function will double rotate node with right/left operations. /// node is S. /// /// S G /// / \ / \ /// A C S C /// / \ ==> / \ / \ /// G B A DC B /// / \ /// D C void _rotateRightLeft(AvlNode<V> node) { _rotateRight(node.right); _rotateLeft(node); } /// This function will double rotate node with left/right operations. /// node is S. /// /// S G /// / \ / \ /// C A C S /// / \ ==> / \ / \ /// B G B CD A /// / \ /// C D void _rotateLeftRight(AvlNode<V> node) { _rotateLeft(node.left); _rotateRight(node); } @override bool addAll(Iterable<V> items) { bool modified = false; for (final item in items) { if (add(item)) { modified = true; } } return modified; } @override AvlTreeSet<T> cast<T>() { // TODO(codefu): Dart 2.0 requires this method to be implemented. throw UnimplementedError('cast'); } @override void clear() { _length = 0; _root = null; ++_modCount; } @override bool containsAll(Iterable<Object> items) { for (final item in items) { if (!contains(item)) return false; } return true; } @override bool remove(Object item) { if (item is! V) return false; AvlNode<V> x = _getNode(item); if (x != null) { _removeNode(x); return true; } return false; } void _removeNode(AvlNode<V> node) { AvlNode<V> y, w; ++_modCount; --_length; // note: if you read wikipedia, it states remove the node if its a leaf, // otherwise, replace it with its predecessor or successor. We're not. if (node._right == null || node.right._left == null) { // simple solutions if (node.right != null) { y = node.right; y._parent = node.parent; y._balanceFactor = node._balanceFactor - 1; y._left = node.left; if (y.left != null) { y.left._parent = y; } } else if (node.left != null) { y = node.left; y._parent = node.parent; y._balanceFactor = node._balanceFactor + 1; } else { y = null; } if (_root == node) { _root = y; } else if (node.parent._left == node) { node.parent._left = y; if (y == null) { // account for leaf deletions changing the balance node.parent._balanceFactor += 1; y = node.parent; // start searching from here; } } else { node.parent._right = y; if (y == null) { node.parent._balanceFactor -= 1; y = node.parent; } } w = y; } else { // This node is not a leaf; we should find the successor node, swap //it with this* and then update the balance factors. y = node.successor; y._left = node.left; if (y.left != null) { y.left._parent = y; } w = y.parent; w._left = y.right; if (w.left != null) { w.left._parent = w; } // known: we're removing from the left w._balanceFactor += 1; // known due to test for n->r->l above y._right = node.right; y.right._parent = y; y._balanceFactor = node._balanceFactor; y._parent = node.parent; if (_root == node) { _root = y; } else if (node.parent._left == node) { node.parent._left = y; } else { node.parent._right = y; } } // Safe to kill node now; its free to go. node._balanceFactor = 0; node._left = node._right = node._parent = null; node.object = null; // Recalculate max values all the way to the top. node = w; while (node != null) { node = node.parent; } // Re-balance to the top, ending early if OK node = w; while (node != null) { if (node._balanceFactor == -1 || node._balanceFactor == 1) { // The height of node hasn't changed; done! break; } if (node._balanceFactor == 2) { // Heavy on the right side; figure out which rotation to perform if (node.right._balanceFactor == -1) { _rotateRightLeft(node); node = node.parent; // old grand-child! if (node._balanceFactor == 1) { node.right._balanceFactor = 0; node.left._balanceFactor = -1; } else if (node._balanceFactor == 0) { node.right._balanceFactor = 0; node.left._balanceFactor = 0; } else { node.right._balanceFactor = 1; node.left._balanceFactor = 0; } node._balanceFactor = 0; } else { // single left-rotation _rotateLeft(node); if (node.parent._balanceFactor == 0) { node.parent._balanceFactor = -1; node._balanceFactor = 1; break; } else { node.parent._balanceFactor = 0; node._balanceFactor = 0; node = node.parent; continue; } } } else if (node._balanceFactor == -2) { // Heavy on the left if (node.left._balanceFactor == 1) { _rotateLeftRight(node); node = node.parent; // old grand-child! if (node._balanceFactor == -1) { node.right._balanceFactor = 1; node.left._balanceFactor = 0; } else if (node._balanceFactor == 0) { node.right._balanceFactor = 0; node.left._balanceFactor = 0; } else { node.right._balanceFactor = 0; node.left._balanceFactor = -1; } node._balanceFactor = 0; } else { _rotateRight(node); if (node.parent._balanceFactor == 0) { node.parent._balanceFactor = 1; node._balanceFactor = -1; break; } else { node.parent._balanceFactor = 0; node._balanceFactor = 0; node = node.parent; continue; } } } // continue up the tree for testing if (node.parent != null) { // The concept of balance here is reverse from addition; since // we are taking away weight from one side or the other (thus // the balance changes in favor of the other side) if (node.parent.left == node) { node.parent._balanceFactor += 1; } else { node.parent._balanceFactor -= 1; } } node = node.parent; } } /// See [Set.removeAll] @override void removeAll(Iterable items) { items.forEach(remove); } /// See [Set.retainAll] @override void retainAll(Iterable<Object> elements) { List<V> chosen = <V>[]; for (final target in elements) { if (target is V && contains(target)) { chosen.add(target); } } clear(); addAll(chosen); } /// See [Set.retainWhere] @override void retainWhere(bool test(V element)) { List<V> chosen = []; for (final target in this) { if (test(target)) { chosen.add(target); } } clear(); addAll(chosen); } /// See [Set.removeWhere] @override void removeWhere(bool test(V element)) { List<V> damned = []; for (final target in this) { if (test(target)) { damned.add(target); } } removeAll(damned); } /// See [IterableBase.first] @override V get first { if (_root == null) return null; AvlNode<V> min = _root.minimumNode; return min != null ? min.object : null; } /// See [IterableBase.last] @override V get last { if (_root == null) return null; AvlNode<V> max = _root.maximumNode; return max != null ? max.object : null; } /// See [Set.lookup] @override V lookup(Object element) { if (element is! V || _root == null) return null; AvlNode<V> x = _root; int compare = 0; while (x != null) { compare = comparator(element, x.object); if (compare == 0) { return x.object; } else if (compare < 0) { x = x.left; } else { x = x.right; } } return null; } @override V nearest(V object, {TreeSearch nearestOption = TreeSearch.NEAREST}) { AvlNode<V> found = _searchNearest(object, option: nearestOption); return (found != null) ? found.object : null; } /// Search the tree for the matching element, or the 'nearest' node. /// NOTE: [BinaryTree.comparator] needs to have finer granulatity than -1,0,1 /// in order for this to return something that's meaningful. AvlNode<V> _searchNearest(V element, {TreeSearch option = TreeSearch.NEAREST}) { if (element == null || _root == null) { return null; } AvlNode<V> x = _root; AvlNode<V> previous; int compare = 0; while (x != null) { previous = x; compare = comparator(element, x.object); if (compare == 0) { return x; } else if (compare < 0) { x = x.left; } else { x = x.right; } } if (option == TreeSearch.GREATER_THAN) { return (compare < 0) ? previous : previous.successor; } else if (option == TreeSearch.LESS_THAN) { return (compare < 0) ? previous.predecessor : previous; } // Default: nearest absolute value // Fell off the tree looking for the exact match; now we need // to find the nearest element. x = (compare < 0) ? previous.predecessor : previous.successor; if (x == null) { return previous; } int otherCompare = comparator(element, x.object); if (compare < 0) { return compare.abs() < otherCompare ? previous : x; } return otherCompare.abs() < compare ? x : previous; } // // [IterableBase]<V> Methods // /// See [IterableBase.iterator] @override BidirectionalIterator<V> get iterator => _AvlTreeIterator._(this); /// See [TreeSet.reverseIterator] @override BidirectionalIterator<V> get reverseIterator => _AvlTreeIterator._(this, reversed: true); /// See [TreeSet.fromIterator] @override BidirectionalIterator<V> fromIterator(V anchor, {bool reversed = false, bool inclusive = true}) => _AvlTreeIterator<V>._(this, anchorObject: anchor, reversed: reversed, inclusive: inclusive); /// See [IterableBase.contains] @override bool contains(Object object) { AvlNode<V> x = _getNode(object); return x != null; } // // [Set] methods // /// See [Set.intersection] @override Set<V> intersection(Set<Object> other) { TreeSet<V> set = TreeSet(comparator: comparator); // Optimized for sorted sets if (other is TreeSet<V>) { var i1 = iterator; var i2 = other.iterator; var hasMore1 = i1.moveNext(); var hasMore2 = i2.moveNext(); while (hasMore1 && hasMore2) { var c = comparator(i1.current, i2.current); if (c == 0) { set.add(i1.current); hasMore1 = i1.moveNext(); hasMore2 = i2.moveNext(); } else if (c < 0) { hasMore1 = i1.moveNext(); } else { hasMore2 = i2.moveNext(); } } return set; } // Non-optimized version. for (final target in this) { if (other.contains(target)) { set.add(target); } } return set; } /// See [Set.union] @override Set<V> union(Set<V> other) { TreeSet<V> set = TreeSet(comparator: comparator); if (other is TreeSet) { var i1 = iterator; var i2 = other.iterator; var hasMore1 = i1.moveNext(); var hasMore2 = i2.moveNext(); while (hasMore1 && hasMore2) { var c = comparator(i1.current, i2.current); if (c == 0) { set.add(i1.current); hasMore1 = i1.moveNext(); hasMore2 = i2.moveNext(); } else if (c < 0) { set.add(i1.current); hasMore1 = i1.moveNext(); } else { set.add(i2.current); hasMore2 = i2.moveNext(); } } if (hasMore1 || hasMore2) { i1 = hasMore1 ? i1 : i2; do { set.add(i1.current); } while (i1.moveNext()); } return set; } // Non-optimized version. return set..addAll(this)..addAll(other); } /// See [Set.difference] @override Set<V> difference(Set<Object> other) { TreeSet<V> set = TreeSet(comparator: comparator); if (other is TreeSet) { var i1 = iterator; var i2 = other.iterator; var hasMore1 = i1.moveNext(); var hasMore2 = i2.moveNext(); while (hasMore1 && hasMore2) { var c = comparator(i1.current, i2.current); if (c == 0) { hasMore1 = i1.moveNext(); hasMore2 = i2.moveNext(); } else if (c < 0) { set.add(i1.current); hasMore1 = i1.moveNext(); } else { hasMore2 = i2.moveNext(); } } if (hasMore1) { do { set.add(i1.current); } while (i1.moveNext()); } return set; } // Non-optimized version. for (final target in this) { if (!other.contains(target)) { set.add(target); } } return set; } @visibleForTesting AvlNode<V> getNode(V object) => _getNode(object); } typedef _IteratorMove = bool Function(); /// This iterator either starts at the beginning or end (see [TreeSet.iterator] /// and [TreeSet.reverseIterator]) or from an anchor point in the set (see /// [TreeSet.fromIterator]). When using fromIterator, the inital anchor point /// is included in the first movement (either [moveNext] or [movePrevious]) but /// can optionally be excluded in the constructor. class _AvlTreeIterator<V> implements BidirectionalIterator<V> { _AvlTreeIterator._(this.tree, {this.reversed = false, this.inclusive = true, this.anchorObject}) : _modCountGuard = tree._modCount { if (anchorObject == null || tree.isEmpty) { // If the anchor is far left or right, we're just a normal iterator. state = reversed ? RIGHT : LEFT; _moveNext = reversed ? _movePreviousNormal : _moveNextNormal; _movePrevious = reversed ? _moveNextNormal : _movePreviousNormal; return; } state = WALK; // Else we've got an anchor we have to worry about initalizing from. // This isn't known till the caller actually performs a previous/next. _moveNext = () { _current = tree._searchNearest(anchorObject, option: reversed ? TreeSearch.LESS_THAN : TreeSearch.GREATER_THAN); _moveNext = reversed ? _movePreviousNormal : _moveNextNormal; _movePrevious = reversed ? _moveNextNormal : _movePreviousNormal; if (_current == null) { state = reversed ? LEFT : RIGHT; } else if (tree.comparator(_current.object, anchorObject) == 0 && !inclusive) { _moveNext(); } return state == WALK; }; _movePrevious = () { _current = tree._searchNearest(anchorObject, option: reversed ? TreeSearch.GREATER_THAN : TreeSearch.LESS_THAN); _moveNext = reversed ? _movePreviousNormal : _moveNextNormal; _movePrevious = reversed ? _moveNextNormal : _movePreviousNormal; if (_current == null) { state = reversed ? RIGHT : LEFT; } else if (tree.comparator(_current.object, anchorObject) == 0 && !inclusive) { _movePrevious(); } return state == WALK; }; } static const LEFT = -1; static const WALK = 0; static const RIGHT = 1; final bool reversed; final AvlTreeSet<V> tree; final int _modCountGuard; final V anchorObject; final bool inclusive; _IteratorMove _moveNext; _IteratorMove _movePrevious; int state; _TreeNode<V> _current; @override V get current => (state != WALK || _current == null) ? null : _current.object; @override bool moveNext() => _moveNext(); @override bool movePrevious() => _movePrevious(); bool _moveNextNormal() { if (_modCountGuard != tree._modCount) { throw ConcurrentModificationError(tree); } if (state == RIGHT || tree.isEmpty) return false; switch (state) { case LEFT: _current = tree._root.minimumNode; state = WALK; return true; case WALK: default: _current = _current.successor; if (_current == null) { state = RIGHT; } return state == WALK; } } bool _movePreviousNormal() { if (_modCountGuard != tree._modCount) { throw ConcurrentModificationError(tree); } if (state == LEFT || tree.isEmpty) return false; switch (state) { case RIGHT: _current = tree._root.maximumNode; state = WALK; return true; case WALK: default: _current = _current.predecessor; if (_current == null) { state = LEFT; } return state == WALK; } } } /// Private class used to track element insertions in the [TreeSet]. class AvlNode<V> extends _TreeNode<V> { AvlNode({V object}) : super(object: object); AvlNode<V> _left; AvlNode<V> _right; // TODO(codefu): Remove need for [parent]; this is just an implementation note AvlNode<V> _parent; int _balanceFactor = 0; @override AvlNode<V> get left => _left; @override AvlNode<V> get right => _right; @override AvlNode<V> get parent => _parent; int get balance => _balanceFactor; @override String toString() => '(b:$balance o: $object l:${left != null} r:${right != null})'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/collection/bimap.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:collection'; /// A bi-directional map whose key-value pairs form a one-to-one /// correspondence. BiMaps support an `inverse` property which gives access to /// an inverted view of the map, such that there is a mapping (v, k) for each /// pair (k, v) in the original map. Since a one-to-one key-value invariant /// applies, it is an error to insert duplicate values into this map. It is /// also an error to insert null keys or values into this map. abstract class BiMap<K, V> implements Map<K, V> { /// Creates a BiMap instance with the default implementation. factory BiMap() => HashBiMap(); /// Adds an association between key and value. /// /// Throws [ArgumentError] if an association involving [value] exists in the /// map; otherwise, the association is inserted, overwriting any existing /// association for the key. @override void operator []=(K key, V value); /// Replaces any existing associations(s) involving key and value. /// /// If an association involving [key] or [value] exists in the map, it is /// removed. void replace(K key, V value); /// Returns the inverse of this map, with key-value pairs (v, k) for each pair /// (k, v) in this map. BiMap<V, K> get inverse; } /// A hash-table based implementation of BiMap. class HashBiMap<K, V> implements BiMap<K, V> { HashBiMap() : this._from(HashMap(), HashMap()); HashBiMap._from(this._map, this._inverse); final Map<K, V> _map; final Map<V, K> _inverse; BiMap<V, K> _cached; @override V operator [](Object key) => _map[key]; @override void operator []=(K key, V value) { _add(key, value, false); } @override void replace(K key, V value) { _add(key, value, true); } @override void addAll(Map<K, V> other) => other.forEach((k, v) => _add(k, v, false)); @override bool containsKey(Object key) => _map.containsKey(key); @override bool containsValue(Object value) => _inverse.containsKey(value); @override void forEach(void f(K key, V value)) => _map.forEach(f); @override bool get isEmpty => _map.isEmpty; @override bool get isNotEmpty => _map.isNotEmpty; @override Iterable<K> get keys => _map.keys; @override int get length => _map.length; @override Iterable<V> get values => _inverse.keys; @override BiMap<V, K> get inverse => _cached ??= HashBiMap._from(_inverse, _map); @override void addEntries(Iterable<MapEntry<K, V>> entries) { for (final entry in entries) { _add(entry.key, entry.value, false); } } @override Map<K2, V2> cast<K2, V2>() { // TODO(cbracken): Dart 2.0 requires this method to be implemented. throw UnimplementedError('cast'); } @override Iterable<MapEntry<K, V>> get entries => _map.entries; @override Map<K2, V2> map<K2, V2>(MapEntry<K2, V2> transform(K key, V value)) => _map.map(transform); @override V putIfAbsent(K key, V ifAbsent()) { var value = _map[key]; if (value != null) return value; if (!_map.containsKey(key)) return _add(key, ifAbsent(), false); return null; } @override V remove(Object key) { _inverse.remove(_map[key]); return _map.remove(key); } @override void removeWhere(bool test(K key, V value)) { _inverse.removeWhere((v, k) => test(k, v)); _map.removeWhere(test); } @override V update(K key, V update(V value), {V ifAbsent()}) { var value = _map[key]; if (value != null) { return _add(key, update(value), true); } else { if (ifAbsent == null) { throw ArgumentError.value(key, 'key', 'Key not in map'); } return _add(key, ifAbsent(), false); } } @override void updateAll(V update(K key, V value)) { for (final key in keys) { _add(key, update(key, _map[key]), true); } } @override void clear() { _map.clear(); _inverse.clear(); } V _add(K key, V value, bool replace) { if (key == null) throw ArgumentError('null key'); if (value == null) throw ArgumentError('null value'); var oldValue = _map[key]; if (oldValue == value) return value; if (_inverse.containsKey(value)) { if (!replace) throw ArgumentError('Mapping for $value exists'); _map.remove(_inverse[value]); } _inverse.remove(oldValue); _map[key] = value; _inverse[value] = key; return value; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/collection
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/collection/delegates/queue.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:collection' show Queue; import 'iterable.dart'; /// An implementation of [Queue] that delegates all methods to another [Queue]. /// For instance you can create a FruitQueue like this : /// /// class FruitQueue extends DelegatingQueue<Fruit> { /// final Queue<Fruit> _fruits = Queue<Fruit>(); /// /// Queue<Fruit> get delegate => _fruits; /// /// // custom methods /// } abstract class DelegatingQueue<E> extends DelegatingIterable<E> implements Queue<E> { @override Queue<E> get delegate; @override void add(E value) => delegate.add(value); @override void addAll(Iterable<E> iterable) => delegate.addAll(iterable); @override void addFirst(E value) => delegate.addFirst(value); @override void addLast(E value) => delegate.addLast(value); @override DelegatingQueue<T> cast<T>() { // TODO(cbracken): Dart 2.0 requires this method to be implemented. throw UnimplementedError('cast'); } @override void clear() => delegate.clear(); @override bool remove(Object object) => delegate.remove(object); @override E removeFirst() => delegate.removeFirst(); @override E removeLast() => delegate.removeLast(); @override void removeWhere(bool test(E element)) => delegate.removeWhere(test); @override void retainWhere(bool test(E element)) => delegate.retainWhere(test); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/collection
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/collection/delegates/map.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// An implementation of [Map] that delegates all methods to another [Map]. /// For instance you can create a FruitMap like this : /// /// class FruitMap extends DelegatingMap<String, Fruit> { /// final Map<String, Fruit> _fruits = {}; /// /// Map<String, Fruit> get delegate => _fruits; /// /// // custom methods /// } abstract class DelegatingMap<K, V> implements Map<K, V> { Map<K, V> get delegate; @override V operator [](Object key) => delegate[key]; @override void operator []=(K key, V value) { delegate[key] = value; } @override void addAll(Map<K, V> other) => delegate.addAll(other); @override void addEntries(Iterable<Object> entries) { // TODO(cbracken): Dart 2.0 requires this method to be implemented. // Change Iterable<Object> to Iterable<MapEntry<K, V>> when // the MapEntry class has been added. throw UnimplementedError('addEntries'); } @override Map<K2, V2> cast<K2, V2>() { // TODO(cbracken): Dart 2.0 requires this method to be implemented. throw UnimplementedError('cast'); } @override void clear() => delegate.clear(); @override bool containsKey(Object key) => delegate.containsKey(key); @override bool containsValue(Object value) => delegate.containsValue(value); @override Iterable<Null> get entries { // TODO(cbracken): Dart 2.0 requires this method to be implemented. // Change Iterable<Null> to Iterable<MapEntry<K, V>> when // the MapEntry class has been added. throw UnimplementedError('entries'); } @override void forEach(void f(K key, V value)) => delegate.forEach(f); @override bool get isEmpty => delegate.isEmpty; @override bool get isNotEmpty => delegate.isNotEmpty; @override Iterable<K> get keys => delegate.keys; @override int get length => delegate.length; @override Map<K2, V2> map<K2, V2>(Object transform(K key, V value)) { // TODO(cbracken): Dart 2.0 requires this method to be implemented. // Change Object to MapEntry<K2, V2> when // the MapEntry class has been added. throw UnimplementedError('map'); } @override V putIfAbsent(K key, V ifAbsent()) => delegate.putIfAbsent(key, ifAbsent); @override V remove(Object key) => delegate.remove(key); @override void removeWhere(bool test(K key, V value)) { // TODO(cbracken): Dart 2.0 requires this method to be implemented. throw UnimplementedError('removeWhere'); } @override V update(K key, V update(V value), {V ifAbsent()}) { // TODO(cbracken): Dart 2.0 requires this method to be implemented. throw UnimplementedError('update'); } @override void updateAll(V update(K key, V value)) { // TODO(cbracken): Dart 2.0 requires this method to be implemented. throw UnimplementedError('updateAll'); } @override Iterable<V> get values => delegate.values; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/collection
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/collection/delegates/list.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:math' show Random; import 'iterable.dart'; /// An implementation of [List] that delegates all methods to another [List]. /// For instance you can create a FruitList like this : /// /// class FruitList extends DelegatingList<Fruit> { /// final List<Fruit> _fruits = []; /// /// List<Fruit> get delegate => _fruits; /// /// // custom methods /// } abstract class DelegatingList<E> extends DelegatingIterable<E> implements List<E> { @override List<E> get delegate; @override E operator [](int index) => delegate[index]; @override void operator []=(int index, E value) { delegate[index] = value; } @override List<E> operator +(List<E> other) => delegate + other; @override void add(E value) => delegate.add(value); @override void addAll(Iterable<E> iterable) => delegate.addAll(iterable); @override Map<int, E> asMap() => delegate.asMap(); @override DelegatingList<T> cast<T>() { // TODO(cbracken): Dart 2.0 requires this method to be implemented. throw UnimplementedError('cast'); } @override void clear() => delegate.clear(); @override void fillRange(int start, int end, [E fillValue]) => delegate.fillRange(start, end, fillValue); @override set first(E element) { if (isEmpty) throw RangeError.index(0, this); this[0] = element; } @override Iterable<E> getRange(int start, int end) => delegate.getRange(start, end); @override int indexOf(E element, [int start = 0]) => delegate.indexOf(element, start); @override int indexWhere(bool test(E element), [int start = 0]) => delegate.indexWhere(test, start); @override void insert(int index, E element) => delegate.insert(index, element); @override void insertAll(int index, Iterable<E> iterable) => delegate.insertAll(index, iterable); @override set last(E element) { if (isEmpty) throw RangeError.index(0, this); this[length - 1] = element; } @override int lastIndexOf(E element, [int start]) => delegate.lastIndexOf(element, start); @override int lastIndexWhere(bool test(E element), [int start]) => delegate.lastIndexWhere(test, start); @override set length(int newLength) { delegate.length = newLength; } @override bool remove(Object value) => delegate.remove(value); @override E removeAt(int index) => delegate.removeAt(index); @override E removeLast() => delegate.removeLast(); @override void removeRange(int start, int end) => delegate.removeRange(start, end); @override void removeWhere(bool test(E element)) => delegate.removeWhere(test); @override void replaceRange(int start, int end, Iterable<E> iterable) => delegate.replaceRange(start, end, iterable); @override void retainWhere(bool test(E element)) => delegate.retainWhere(test); @override Iterable<E> get reversed => delegate.reversed; @override void setAll(int index, Iterable<E> iterable) => delegate.setAll(index, iterable); @override void setRange(int start, int end, Iterable<E> iterable, [int skipCount = 0]) => delegate.setRange(start, end, iterable, skipCount); @override void shuffle([Random random]) => delegate.shuffle(random); @override void sort([int compare(E a, E b)]) => delegate.sort(compare); @override List<E> sublist(int start, [int end]) => delegate.sublist(start, end); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/collection
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/collection/delegates/iterable.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// An implementation of [Iterable] that delegates all methods to another /// [Iterable]. For instance you can create a FruitIterable like this : /// /// class FruitIterable extends DelegatingIterable<Fruit> { /// final Iterable<Fruit> _fruits = []; /// /// Iterable<Fruit> get delegate => _fruits; /// /// // custom methods /// } abstract class DelegatingIterable<E> implements Iterable<E> { Iterable<E> get delegate; @override bool any(bool test(E element)) => delegate.any(test); @override Iterable<T> cast<T>() { // TODO(cbracken): Dart 2.0 requires this method to be implemented. throw UnimplementedError('cast'); } @override bool contains(Object element) => delegate.contains(element); @override E elementAt(int index) => delegate.elementAt(index); @override bool every(bool test(E element)) => delegate.every(test); @override Iterable<T> expand<T>(Iterable<T> f(E element)) => delegate.expand(f); @override E get first => delegate.first; @override E firstWhere(bool test(E element), {E orElse()}) => delegate.firstWhere(test, orElse: orElse); @override T fold<T>(T initialValue, T combine(T previousValue, E element)) => delegate.fold(initialValue, combine); @override Iterable<E> followedBy(Iterable<E> other) => delegate.followedBy(other); @override void forEach(void f(E element)) => delegate.forEach(f); @override bool get isEmpty => delegate.isEmpty; @override bool get isNotEmpty => delegate.isNotEmpty; @override Iterator<E> get iterator => delegate.iterator; @override String join([String separator = '']) => delegate.join(separator); @override E get last => delegate.last; @override E lastWhere(bool test(E element), {E orElse()}) => delegate.lastWhere(test, orElse: orElse); @override int get length => delegate.length; @override Iterable<T> map<T>(T f(E e)) => delegate.map(f); @override E reduce(E combine(E value, E element)) => delegate.reduce(combine); @override E get single => delegate.single; @override E singleWhere(bool test(E element), {E orElse()}) => delegate.singleWhere(test, orElse: orElse); @override Iterable<E> skip(int n) => delegate.skip(n); @override Iterable<E> skipWhile(bool test(E value)) => delegate.skipWhile(test); @override Iterable<E> take(int n) => delegate.take(n); @override Iterable<E> takeWhile(bool test(E value)) => delegate.takeWhile(test); @override List<E> toList({bool growable = true}) => delegate.toList(growable: growable); @override Set<E> toSet() => delegate.toSet(); @override Iterable<E> where(bool test(E element)) => delegate.where(test); @override Iterable<T> whereType<T>() { // TODO(cbracken): Dart 2.0 requires this method to be implemented. throw UnimplementedError('whereType'); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/collection
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/collection/delegates/set.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'iterable.dart'; /// An implementation of [Set] that delegates all methods to another [Set]. /// For instance you can create a FruitSet like this : /// /// class FruitSet extends DelegatingSet<Fruit> { /// final Set<Fruit> _fruits = Set<Fruit>(); /// /// Set<Fruit> get delegate => _fruits; /// /// // custom methods /// } abstract class DelegatingSet<E> extends DelegatingIterable<E> implements Set<E> { @override Set<E> get delegate; @override bool add(E value) => delegate.add(value); @override void addAll(Iterable<E> elements) => delegate.addAll(elements); @override DelegatingSet<T> cast<T>() { // TODO(cbracken): Dart 2.0 requires this method to be implemented. throw UnimplementedError('cast'); } @override void clear() => delegate.clear(); @override bool containsAll(Iterable<Object> other) => delegate.containsAll(other); @override Set<E> difference(Set<Object> other) => delegate.difference(other); @override Set<E> intersection(Set<Object> other) => delegate.intersection(other); @override E lookup(Object object) => delegate.lookup(object); @override bool remove(Object value) => delegate.remove(value); @override void removeAll(Iterable<Object> elements) => delegate.removeAll(elements); @override void removeWhere(bool test(E element)) => delegate.removeWhere(test); @override void retainAll(Iterable<Object> elements) => delegate.retainAll(elements); @override void retainWhere(bool test(E element)) => delegate.retainWhere(test); @override Set<E> union(Set<E> other) => delegate.union(other); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/iterables/generating_iterable.dart
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:collection'; typedef _Initial<T> = T Function(); typedef _Next<T> = T Function(T value); Iterable generate(initial(), next(o)) => GeneratingIterable(initial, next); /// An Iterable whose first value is the result of [initial] and whose /// subsequent values are generated by passing the current value to the [next] /// function. /// /// The class is useful for creating lazy iterables from object hierarchies and /// graphs. /// /// The initial value and [next] function are required to generate a sequence /// that eventually terminates, otherwise calling methods that expect a finite /// sequence, like `length` or `last`, will cause an infinite loop. /// /// Example: /// /// class Node { /// Node parent; /// /// /// An iterable of node and all ancestors up to the root. /// Iterable<Node> ancestors = /// GeneratingIterable<Node>(() => this, (n) => n.parent); /// /// /// An iterable of the root and the path of nodes to this. The /// /// reverse of ancestors. /// Iterable<Node> path = ancestors.toList().reversed(); /// } /// class GeneratingIterable<T> extends IterableBase<T> { GeneratingIterable(this.initial, this.next); final _Initial<T> initial; final _Next<T> next; @override Iterator<T> get iterator => _GeneratingIterator(initial(), next); } class _GeneratingIterator<T> implements Iterator<T> { _GeneratingIterator(this.object, this.next); final _Next<T> next; T object; bool started = false; @override T get current => started ? object : null; @override bool moveNext() { if (object == null) return false; if (started) { object = next(object); } else { started = true; } return object != null; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/iterables/infinite_iterable.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:collection'; /// A base class for [Iterable]s of infinite length that throws /// [UnsupportedError] for methods that would require the Iterable to /// terminate. abstract class InfiniteIterable<T> extends IterableBase<T> { @override bool get isEmpty => false; @override bool get isNotEmpty => true; @override T get last => throw UnsupportedError('last'); @override int get length => throw UnsupportedError('length'); @override T get single => throw StateError('single'); @override bool every(bool test(T element)) => throw UnsupportedError('every'); @override T1 fold<T1>(T1 initialValue, T1 combine(T1 previousValue, T element)) => throw UnsupportedError('fold'); @override void forEach(void f(T element)) => throw UnsupportedError('forEach'); @override String join([String separator = '']) => throw UnsupportedError('join'); @override T lastWhere(bool test(T value), {T orElse()}) => throw UnsupportedError('lastWhere'); @override T reduce(T combine(T value, T element)) => throw UnsupportedError('reduce'); @override T singleWhere(bool test(T value), {T orElse()}) => throw UnsupportedError('singleWhere'); @override List<T> toList({bool growable = true}) => throw UnsupportedError('toList'); @override Set<T> toSet() => throw UnsupportedError('toSet'); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/iterables/range.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Returns an [Iterable] sequence of [num]s. /// /// If only one argument is provided, [startOrStop] is the upper bound for the /// sequence. If two or more arguments are provided, [stop] is the upper bound. /// /// The sequence starts at 0 if one argument is provided, or [startOrStop] if /// two or more arguments are provided. The sequence increments by 1, or [step] /// if provided. [step] can be negative, in which case the sequence counts down /// from the starting point and [stop] must be less than the starting point so /// that it becomes the lower bound. Iterable<num> range(num startOrStop, [num stop, num step]) sync* { final start = stop == null ? 0 : startOrStop; stop ??= startOrStop; step ??= 1; if (step == 0) throw ArgumentError('step cannot be 0'); if (step > 0 && stop < start) { throw ArgumentError('if step is positive, stop must be greater than start'); } if (step < 0 && stop > start) { throw ArgumentError('if step is negative, stop must be less than start'); } for (num value = start; step < 0 ? value > stop : value < stop; value += step) { yield value; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/iterables/min_max.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Returns the maximum value in [i], according to the order specified by the /// [compare] function, or `null` if [i] is empty. /// /// The compare function must act as a [Comparator]. If [compare] is omitted, /// [Comparable.compare] is used. If [i] contains null elements, an exception /// will be thrown. T max<T>(Iterable<T> i, [Comparator<T> compare]) { if (i.isEmpty) return null; final Comparator<T> _compare = compare ?? Comparable.compare; return i.reduce((a, b) => _compare(a, b) > 0 ? a : b); } /// Returns the minimum value in [i], according to the order specified by the /// [compare] function, or `null` if [i] is empty. /// /// The compare function must act as a [Comparator]. If [compare] is omitted, /// [Comparable.compare] is used. If [i] contains null elements, an exception /// will be thrown. T min<T>(Iterable<T> i, [Comparator<T> compare]) { if (i.isEmpty) return null; final Comparator<T> _compare = compare ?? Comparable.compare; return i.reduce((a, b) => _compare(a, b) < 0 ? a : b); } /// Returns the minimum and maximum values in [i], according to the order /// specified by the [compare] function, in an [Extent] instance. Always /// returns an [Extent], but [Extent.min] and [Extent.max] may be `null` if [i] /// is empty. /// /// The compare function must act as a [Comparator]. If [compare] is omitted, /// [Comparable.compare] is used. If [i] contains null elements, an exception /// will be thrown. /// /// If [i] is empty, an [Extent] is returned with [:null:] values for [:min:] /// and [:max:], since there are no valid values for them. Extent<T> extent<T>(Iterable<T> i, [Comparator<T> compare]) { if (i.isEmpty) return Extent(null, null); final Comparator<T> _compare = compare ?? Comparable.compare; var iterator = i.iterator; var hasNext = iterator.moveNext(); if (!hasNext) return Extent(null, null); var max = iterator.current; var min = iterator.current; while (iterator.moveNext()) { if (_compare(max, iterator.current) < 0) max = iterator.current; if (_compare(min, iterator.current) > 0) min = iterator.current; } return Extent(min, max); } class Extent<T> { Extent(this.min, this.max); final T min; final T max; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/iterables/concat.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Returns the concatentation of the input iterables. /// /// The returned iterable is a lazily-evaluated view on the input iterables. Iterable<T> concat<T>(Iterable<Iterable<T>> iterables) => iterables.expand((x) => x);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/iterables/enumerate.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:collection'; /// Returns an [Iterable] of [IndexedValue]s where the nth value holds the nth /// element of [iterable] and its index. Iterable<IndexedValue<E>> enumerate<E>(Iterable<E> iterable) => EnumerateIterable<E>(iterable); class IndexedValue<V> { IndexedValue(this.index, this.value); final int index; final V value; @override bool operator ==(other) => other is IndexedValue && other.index == index && other.value == value; @override int get hashCode => index * 31 + value.hashCode; @override String toString() => '($index, $value)'; } /// An [Iterable] of [IndexedValue]s where the nth value holds the nth /// element of [iterable] and its index. See [enumerate]. // This was inspired by MappedIterable internal to Dart collections. class EnumerateIterable<V> extends IterableBase<IndexedValue<V>> { EnumerateIterable(this._iterable); final Iterable<V> _iterable; @override Iterator<IndexedValue<V>> get iterator => EnumerateIterator<V>(_iterable.iterator); // Length related functions are independent of the mapping. @override int get length => _iterable.length; @override bool get isEmpty => _iterable.isEmpty; // Index based lookup can be done before transforming. @override IndexedValue<V> get first => IndexedValue<V>(0, _iterable.first); @override IndexedValue<V> get last => IndexedValue<V>(length - 1, _iterable.last); @override IndexedValue<V> get single => IndexedValue<V>(0, _iterable.single); @override IndexedValue<V> elementAt(int index) => IndexedValue<V>(index, _iterable.elementAt(index)); } /// The [Iterator] returned by [EnumerateIterable.iterator]. class EnumerateIterator<V> extends Iterator<IndexedValue<V>> { EnumerateIterator(this._iterator); final Iterator<V> _iterator; int _index = 0; IndexedValue<V> _current; @override IndexedValue<V> get current => _current; @override bool moveNext() { if (_iterator.moveNext()) { _current = IndexedValue(_index++, _iterator.current); return true; } _current = null; return false; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/iterables/partition.dart
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:collection'; /// Partitions the input iterable into lists of the specified size. Iterable<List<T>> partition<T>(Iterable<T> iterable, int size) { return iterable.isEmpty ? [] : _Partition<T>(iterable, size); } class _Partition<T> extends IterableBase<List<T>> { _Partition(this._iterable, this._size) { if (_size <= 0) throw ArgumentError(_size); } final Iterable<T> _iterable; final int _size; @override Iterator<List<T>> get iterator => _PartitionIterator<T>(_iterable.iterator, _size); } class _PartitionIterator<T> implements Iterator<List<T>> { _PartitionIterator(this._iterator, this._size); final Iterator<T> _iterator; final int _size; List<T> _current; @override List<T> get current => _current; @override bool moveNext() { var newValue = <T>[]; var count = 0; while (count < _size && _iterator.moveNext()) { newValue.add(_iterator.current); count++; } _current = (count > 0) ? newValue : null; return _current != null; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/iterables/merge.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:collection'; /// Returns the result of merging an [Iterable] of [Iterable]s, according to /// the order specified by the [compare] function. This function assumes the /// provided iterables are already sorted according to the provided [compare] /// function. It will not check for this condition or sort the iterables. /// /// The compare function must act as a [Comparator]. If [compare] is omitted, /// [Comparable.compare] is used. /// /// If any of the [iterables] contain null elements, an exception will be /// thrown. Iterable<T> merge<T>(Iterable<Iterable<T>> iterables, [Comparator<T> compare]) { if (iterables.isEmpty) return const <Null>[]; if (iterables.every((i) => i.isEmpty)) return const <Null>[]; return _Merge<T>(iterables, compare ?? Comparable.compare); } class _Merge<T> extends IterableBase<T> { _Merge(this._iterables, this._compare); final Iterable<Iterable<T>> _iterables; final Comparator<T> _compare; @override Iterator<T> get iterator => _MergeIterator<T>( _iterables.map((i) => i.iterator).toList(growable: false), _compare); @override String toString() => toList().toString(); } /// Like [Iterator] but one element ahead. class _IteratorPeeker<T> { _IteratorPeeker(Iterator<T> iterator) : _iterator = iterator, _hasCurrent = iterator.moveNext(); final Iterator<T> _iterator; bool _hasCurrent; void moveNext() { _hasCurrent = _iterator.moveNext(); } T get current => _iterator.current; } class _MergeIterator<T> implements Iterator<T> { _MergeIterator(List<Iterator<T>> iterators, this._compare) : _peekers = iterators.map((i) => _IteratorPeeker(i)).toList(); final List<_IteratorPeeker<T>> _peekers; final Comparator<T> _compare; T _current; @override bool moveNext() { // Pick the peeker that's peeking at the puniest piece _IteratorPeeker<T> minIter; for (final p in _peekers) { if (p._hasCurrent) { if (minIter == null || _compare(p.current, minIter.current) < 0) { minIter = p; } } } if (minIter == null) { return false; } _current = minIter.current; minIter.moveNext(); return true; } @override T get current => _current; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/iterables/cycle.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'infinite_iterable.dart'; /// Returns an [Iterable] that infinitely cycles through the elements of /// [iterable]. If [iterable] is empty, the returned Iterable will also be empty. Iterable<T> cycle<T>(Iterable<T> iterable) => _Cycle<T>(iterable); class _Cycle<T> extends InfiniteIterable<T> { _Cycle(this._iterable); final Iterable<T> _iterable; @override Iterator<T> get iterator => _CycleIterator(_iterable); @override bool get isEmpty => _iterable.isEmpty; @override bool get isNotEmpty => _iterable.isNotEmpty; // TODO(justin): add methods that can be answered by the wrapped iterable } class _CycleIterator<T> implements Iterator<T> { _CycleIterator(Iterable<T> _iterable) : _iterable = _iterable, _iterator = _iterable.iterator; final Iterable<T> _iterable; Iterator<T> _iterator; @override T get current => _iterator.current; @override bool moveNext() { if (!_iterator.moveNext()) { _iterator = _iterable.iterator; return _iterator.moveNext(); } return true; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/iterables/zip.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Returns an [Iterable] of [List]s where the nth element in the returned /// iterable contains the nth element from every Iterable in [iterables]. The /// returned Iterable is as long as the shortest Iterable in the argument. If /// [iterables] is empty, it returns an empty list. Iterable<List<T>> zip<T>(Iterable<Iterable<T>> iterables) sync* { if (iterables.isEmpty) return; final iterators = iterables.map((e) => e.iterator).toList(growable: false); while (iterators.every((e) => e.moveNext())) { yield iterators.map((e) => e.current).toList(growable: false); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/iterables/count.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'infinite_iterable.dart'; /// Returns an infinite [Iterable] of [num]s, starting from [start] and /// increasing by [step]. Iterable<num> count([num start = 0, num step = 1]) => _Count(start, step); class _Count extends InfiniteIterable<num> { _Count(this.start, this.step); final num start, step; @override Iterator<num> get iterator => _CountIterator(start, step); // TODO(justin): return an infinite list for toList() and a special Set // implmentation for toSet()? } class _CountIterator implements Iterator<num> { _CountIterator(this._start, this._step); final num _start, _step; num _current; @override num get current => _current; @override bool moveNext() { _current = (_current == null) ? _start : _current + _step; return true; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/async/countdown_timer.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:async'; /// A simple countdown timer that fires events in regular increments until a /// duration has passed. /// /// CountdownTimer implements [Stream] and sends itself as the event. From the /// timer you can get the [remaining] and [elapsed] time, or [cancel] the /// timer. class CountdownTimer extends Stream<CountdownTimer> { /// Creates a new [CountdownTimer] that fires events in increments of /// [increment], until the [duration] has passed. /// /// [stopwatch] is for testing purposes. If you're using CountdownTimer and /// need to control time in a test, pass a mock or a fake. See [FakeAsync] /// and [FakeStopwatch]. CountdownTimer(Duration duration, this.increment, {Stopwatch stopwatch}) : _duration = duration, _stopwatch = stopwatch ?? Stopwatch(), _controller = StreamController<CountdownTimer>.broadcast(sync: true) { _timer = Timer.periodic(increment, _tick); _stopwatch.start(); } static const _THRESHOLD_MS = 4; final Duration _duration; final Stopwatch _stopwatch; /// The duration between timer events. final Duration increment; final StreamController<CountdownTimer> _controller; Timer _timer; @override StreamSubscription<CountdownTimer> listen(void onData(CountdownTimer event), {Function onError, void onDone(), bool cancelOnError}) => _controller.stream.listen(onData, onError: onError, onDone: onDone); Duration get elapsed => _stopwatch.elapsed; Duration get remaining => _duration - _stopwatch.elapsed; bool get isRunning => _stopwatch.isRunning; void cancel() { _stopwatch.stop(); _timer.cancel(); _controller.close(); } void _tick(Timer timer) { var t = remaining; _controller.add(this); // timers may have a 4ms resolution if (t.inMilliseconds < _THRESHOLD_MS) { cancel(); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/async/stream_buffer.dart
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:async'; /// Underflow errors happen when the socket feeding a buffer is finished while /// there are still blocked readers. Each reader will complete with this error. class UnderflowError extends Error { /// The [message] describes the underflow. UnderflowError([this.message]); final String message; @override String toString() { if (message != null) { return 'StreamBuffer Underflow: $message'; } return 'StreamBuffer Underflow'; } } /// Allow orderly reading of elements from a datastream, such as Socket, which /// might not receive `List<int>` bytes regular chunks. /// /// Example usage: /// /// StreamBuffer<int> buffer = StreamBuffer(); /// Socket.connect('127.0.0.1', 5555).then((sock) => sock.pipe(buffer)); /// buffer.read(100).then((bytes) { /// // do something with 100 bytes; /// }); /// /// Throws [UnderflowError] if [throwOnError] is true. Useful for unexpected /// [Socket] disconnects. class StreamBuffer<T> implements StreamConsumer<List<T>> { /// Create a stream buffer with optional, soft [limit] to the amount of data /// the buffer will hold before pausing the underlying stream. A limit of 0 /// means no buffer limits. StreamBuffer({bool throwOnError = false, int limit = 0}) : _throwOnError = throwOnError, _limit = limit; int _offset = 0; int _counter = 0; // sum(_chunks[*].length) - _offset final List<T> _chunks = []; final List<_ReaderInWaiting<List<T>>> _readers = []; StreamSubscription<List<T>> _sub; final bool _throwOnError; Stream _currentStream; int _limit = 0; set limit(int limit) { _limit = limit; if (_sub != null) { if (!limited || _counter < limit) { _sub.resume(); } else { _sub.pause(); } } } int get limit => _limit; bool get limited => _limit > 0; /// The amount of unread data buffered. int get buffered => _counter; List<T> _consume(int size) { var follower = 0; var ret = List<T>(size); var leftToRead = size; while (leftToRead > 0) { var chunk = _chunks.first; var listCap = (chunk is List) ? chunk.length - _offset : 1; var subsize = leftToRead > listCap ? listCap : leftToRead; if (chunk is List) { ret.setRange(follower, follower + subsize, chunk.getRange(_offset, _offset + subsize)); } else { ret[follower] = chunk; } follower += subsize; _offset += subsize; _counter -= subsize; leftToRead -= subsize; if (!(chunk is List && _offset < chunk.length)) { _offset = 0; _chunks.removeAt(0); } } if (limited && _sub.isPaused && _counter < limit) { _sub.resume(); } return ret; } /// Read fully [size] bytes from the stream and return in the future. /// /// Throws [ArgumentError] if size is larger than optional buffer [limit]. Future<List<T>> read(int size) { if (limited && size > limit) { throw ArgumentError('Cannot read $size with limit $limit'); } // If we have enough data to consume and there are no other readers, then // we can return immediately. if (size <= buffered && _readers.isEmpty) { return Future.value(_consume(size)); } final completer = Completer<List<T>>(); _readers.add(_ReaderInWaiting<List<T>>(size, completer)); return completer.future; } @override Future addStream(Stream<List<T>> stream) { var lastStream = _currentStream ?? stream; if (_sub != null) { _sub.cancel(); } _currentStream = stream; final streamDone = Completer<Null>(); _sub = stream.listen((items) { _chunks.addAll(items); _counter += items is List ? items.length : 1; if (limited && _counter >= limit) { _sub.pause(); } while (_readers.isNotEmpty && _readers.first.size <= _counter) { var waiting = _readers.removeAt(0); waiting.completer.complete(_consume(waiting.size)); } }, onDone: () { // User is piping in a new stream if (stream == lastStream && _throwOnError) { _closed(UnderflowError()); } streamDone.complete(); }, onError: (e, stack) { _closed(e, stack); }); return streamDone.future; } void _closed(e, [StackTrace stack]) { for (final reader in _readers) { if (!reader.completer.isCompleted) { reader.completer.completeError(e, stack); } } _readers.clear(); } @override Future close() { Future ret; if (_sub != null) { ret = _sub.cancel(); _sub = null; } return ret ?? Future.value(); } } class _ReaderInWaiting<T> { _ReaderInWaiting(this.size, this.completer); int size; Completer<T> completer; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/async/metronome.dart
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:async'; import 'package:quiver/time.dart'; /// A stream of [DateTime] events at [interval]s centered on [anchor]. /// /// This stream accounts for drift but only guarantees that events are /// delivered on or after the interval. If the system is busy for longer than /// two [interval]s, only one will be delivered. /// /// [anchor] defaults to [clock.now], which means the stream represents a /// self-correcting periodic timer. If anchor is the epoch, then the stream is /// synchronized to wall-clock time. It can be anchored anywhere in time, but /// this does not delay the first delivery. /// /// Examples: /// /// new Metronome.epoch(aMinute).listen((d) => print(d)); /// /// Could print the following stream of events, anchored by epoch, till the /// stream is canceled: /// /// 2014-05-04 14:06:00.001 /// 2014-05-04 14:07:00.000 /// 2014-05-04 14:08:00.003 /// ... /// /// Example anchored in the future (now = 2014-05-05 20:06:00.123) /// /// new IsochronousStream.periodic(aMillisecond * 100, /// anchorMs: DateTime.parse("2014-05-05 21:07:00")) /// .listen(print); /// /// 2014-05-04 20:06:00.223 /// 2014-05-04 20:06:00.324 /// 2014-05-04 20:06:00.423 /// ... class Metronome extends Stream<DateTime> { Metronome.epoch(Duration interval, {Clock clock = const Clock()}) : this._(interval, clock: clock, anchor: _epoch); Metronome.periodic(Duration interval, {Clock clock = const Clock(), DateTime anchor}) : this._(interval, clock: clock, anchor: anchor); Metronome._(this.interval, {this.clock = const Clock(), this.anchor}) : _intervalMs = interval.inMilliseconds, _anchorMs = (anchor ?? clock.now()).millisecondsSinceEpoch { _controller = StreamController<DateTime>.broadcast( sync: true, onCancel: () { _timer.cancel(); }, onListen: () { _startTimer(clock.now()); }); } static final DateTime _epoch = DateTime.fromMillisecondsSinceEpoch(0); final Clock clock; final Duration interval; final DateTime anchor; Timer _timer; StreamController<DateTime> _controller; final int _intervalMs; final int _anchorMs; @override bool get isBroadcast => true; @override StreamSubscription<DateTime> listen(void onData(DateTime event), {Function onError, void onDone(), bool cancelOnError}) => _controller.stream.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); void _startTimer(DateTime now) { var delay = _intervalMs - ((now.millisecondsSinceEpoch - _anchorMs) % _intervalMs); _timer = Timer(Duration(milliseconds: delay), _tickDate); } void _tickDate() { // Hey now, what's all this hinky clock.now() calls? Simple, if the workers // on the receiving end of _controller.add() take a non-zero amount of time // to do their thing (e.g. rendering a large scene with canvas), the next // timer must be adjusted to account for the lapsed time. _controller.add(clock.now()); _startTimer(clock.now()); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/async/concat.dart
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:async'; /// Returns the concatentation of the input streams. /// /// When the returned stream is listened to, the [streams] are iterated through /// asynchronously, forwarding all events (both data and error) for the current /// stream to the returned stream before advancing the iterator and listening /// to the next stream. If advancing the iterator throws an error, the /// returned stream ends immediately with that error. /// /// Pausing and resuming the returned stream's subscriptions will pause and /// resume the subscription of the current stream being listened to. /// /// Note: Events from pre-existing broadcast streams which occur before the /// stream is reached by the iteration will be dropped. /// /// Example: /// /// concat(files.map((file) => /// file.openRead().transform(const LineSplitter()))) Stream<T> concat<T>(Iterable<Stream<T>> streams) => _ConcatStream(streams); class _ConcatStream<T> extends Stream<T> { _ConcatStream(Iterable<Stream<T>> streams) : _streams = streams; final Iterable<Stream<T>> _streams; @override StreamSubscription<T> listen(void onData(T data), {Function onError, void onDone(), bool cancelOnError}) { cancelOnError = true == cancelOnError; StreamSubscription<T> currentSubscription; StreamController<T> controller; final iterator = _streams.iterator; void nextStream() { bool hasNext; try { hasNext = iterator.moveNext(); } catch (e, s) { controller ..addError(e, s) ..close(); return; } if (hasNext) { currentSubscription = iterator.current.listen(controller.add, onError: controller.addError, onDone: nextStream, cancelOnError: cancelOnError); } else { controller.close(); } } controller = StreamController<T>( onPause: () { currentSubscription?.pause(); }, onResume: () { currentSubscription?.resume(); }, onCancel: () => currentSubscription?.cancel(), ); nextStream(); return controller.stream.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/async/stream_router.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:async'; /// Splits a [Stream] of events into multiple Streams based on a set of /// predicates. /// /// Using StreamRouter differs from [Stream.where] because events are only sent /// to one Stream. If more than one predicate matches the event, the event is /// sent to the stream created by the earlier call to [route]. Events not /// matched by a call to [route] are sent to the [defaultStream]. /// /// Example: /// /// import 'dart:html'; /// import 'package:quiver/async.dart'; /// /// var router = StreamRouter(window.onClick); /// var onRightClick = router.route((e) => e.button == 2); /// var onAltClick = router.route((e) => e.altKey); /// var onOtherClick router.defaultStream; class StreamRouter<T> { /// Create a new StreamRouter that listens to the [incoming] stream. StreamRouter(Stream<T> incoming) : _incoming = incoming { _subscription = _incoming.listen(_handle, onDone: close); } final Stream<T> _incoming; StreamSubscription<T> _subscription; final List<_Route<T>> _routes = <_Route<T>>[]; final StreamController<T> _defaultController = StreamController<T>.broadcast(); /// Events that match [predicate] are sent to the stream created by this /// method, and not sent to any other router streams. Stream<T> route(bool predicate(T event)) { var controller = StreamController<T>.broadcast(); _routes.add(_Route(predicate, controller)); return controller.stream; } Stream<T> get defaultStream => _defaultController.stream; Future close() { return Future.wait(_routes.map((r) => r.controller.close())).then((_) { _subscription.cancel(); }); } void _handle(T event) { var route = _routes.firstWhere((r) => r.predicate(event), orElse: () => null); var controller = (route != null) ? route.controller : _defaultController; controller.add(event); } } typedef _Predicate<T> = bool Function(T event); class _Route<T> { _Route(this.predicate, this.controller); final _Predicate<T> predicate; final StreamController<T> controller; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/async/string.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:async' show Stream; import 'dart:convert' show Encoding, utf8; /// Converts a [Stream] of byte lists to a [String]. Future<String> byteStreamToString(Stream<List<int>> stream, {Encoding encoding = utf8}) { return stream.transform(encoding.decoder).join(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/async/enumerate.dart
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:async'; import 'package:quiver/iterables.dart' show IndexedValue; /// Returns a [Stream] of [IndexedValue]s where the nth value holds the nth /// element of [stream] and its index. Stream<IndexedValue<T>> enumerate<T>(Stream<T> stream) { var index = 0; return stream.map((value) => IndexedValue<T>(index++, value)); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/async/future_stream.dart
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:async'; /// A Stream that will emit the same values as the stream returned by [future] /// once [future] completes. /// /// If [future] completes to an error, the return value will emit that error /// and then close. /// /// If [broadcast] is true, this will be a broadcast stream. This assumes that /// the stream returned by [future] will be a broadcast stream as well. /// [broadcast] defaults to false. /// /// # Example /// /// This class is useful when you need to retreive some object via a `Future`, /// then return a `Stream` from that object: /// /// var futureOfStream = getResource().then((resource) => resource.stream); /// return FutureStream(futureOfStream); class FutureStream<T> extends Stream<T> { FutureStream(Future<Stream<T>> future, {bool broadcast = false}) { _future = future.then(_identity, onError: (e, stackTrace) { // Since [controller] is synchronous, it's likely that emitting an error // will cause it to be cancelled before we call close. if (_controller != null) { _controller.addError(e, stackTrace); _controller.close(); } _controller = null; }); if (broadcast == true) { _controller = StreamController.broadcast( sync: true, onListen: _onListen, onCancel: _onCancel); } else { _controller = StreamController( sync: true, onListen: _onListen, onCancel: _onCancel); } } static T _identity<T>(T t) => t; Future<Stream<T>> _future; StreamController<T> _controller; StreamSubscription<T> _subscription; void _onListen() { _future.then((stream) { if (_controller == null) return; _subscription = stream.listen(_controller.add, onError: _controller.addError, onDone: _controller.close); }); } void _onCancel() { if (_subscription != null) _subscription.cancel(); _subscription = null; _controller = null; } @override StreamSubscription<T> listen(void onData(T event), {Function onError, void onDone(), bool cancelOnError}) { return _controller.stream.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); } @override bool get isBroadcast => _controller.stream.isBroadcast; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/async/collect.dart
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:async'; /// Returns a stream of completion events for the input [futures]. /// /// Successfully completed futures yield data events, while futures completed /// with errors yield error events. /// /// The iterator obtained from [futures] is only advanced once the previous /// future completes and yields an event. Thus, lazily creating the futures is /// supported, for example: /// /// collect(files.map((file) => file.readAsString())); /// /// If you need to modify [futures], or a backing collection thereof, before /// the returned stream is done, pass a copy instead to avoid a /// [ConcurrentModificationError]: /// /// collect(files.toList().map((file) => file.readAsString())); Stream<T> collect<T>(Iterable<Future<T>> futures) => Stream.fromIterable(futures).asyncMap((f) => f);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/quiver/src/async/iteration.dart
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:async'; /// An asynchronous callback that returns a value. typedef AsyncAction<T, E> = Future<T> Function(E e); /// An asynchronous funcuntion that combines an element [e] with a previous /// value [previous]. typedef AsyncCombiner<T, E> = Future<T> Function(T previous, E e); /// Calls [action] for each item in [iterable] in turn, waiting for the Future /// returned by action to complete. /// /// If the Future completes to [true], iteration continues. /// /// The Future returned completes to [true] if the entire iterable was /// processed, otherwise [false]. /// /// This is deprecated and will be removed in Quiver 3.0.0. It can be replaced /// by [Future.doWhile]. For example: /// /// List<int> myList = ... /// await doWhileAsync(myList, (int i) { /// return i != 5; /// }); /// /// can be replaced by the following code: /// /// List<int> myList = ... /// Iterator<int> it = myList.iterator; /// await Future.doWhile(() { /// if (it.moveNext()) { /// return it.current != 5; /// } /// return false; /// }); @Deprecated('Use Future.doWhile from dart:async. Will be removed in 3.0.0.') Future<bool> doWhileAsync<T>( Iterable<T> iterable, AsyncAction<bool, T> action) => _doWhileAsync(iterable.iterator, action); Future<bool> _doWhileAsync<T>( Iterator<T> iterator, AsyncAction<bool, T> action) async { if (iterator.moveNext()) { return await action(iterator.current) ? _doWhileAsync(iterator, action) : false; } return true; } /// Reduces a collection to a single value by iteratively combining elements of /// the collection using the provided [combine] function. Similar to /// [Iterable.reduce], except that [combine] is an async function that returns /// a [Future]. /// /// This is deprecated and will be removed in Quiver 3.0.0. It can be replaced /// with [Future.forEach] as follows: /// /// List<int> myList = ... /// int sum = await reduceAsync(myList, 0, (int a, int b) { /// return a + b; /// }); /// /// can be replaced by the following code: /// /// List<int> myList = ... /// int sum = 0; /// await Future.forEach(myList, (int i) { /// sum += i; /// }); @Deprecated('Use Future.doWhile from dart:async. Will be removed in 3.0.0.') Future<S> reduceAsync<S, T>( Iterable<T> iterable, S initialValue, AsyncCombiner<S, T> combine) => _reduceAsync(iterable.iterator, initialValue, combine); Future<S> _reduceAsync<S, T>( Iterator<T> iterator, S current, AsyncCombiner<S, T> combine) async { if (iterator.moveNext()) { var result = await combine(current, iterator.current); return _reduceAsync(iterator, result, combine); } return current; } /// Schedules calls to [action] for each element in [iterable]. No more than /// [maxTasks] calls to [action] will be pending at once. /// /// This is deprecated and will be removed in Quiver 3.0.0. When the [maxTasks] /// argument is left defaulted, it can be replaced with [Future.forEach] as /// follows: /// /// List<int> myList = ... /// await forEachAsync(myList, (int i) { /// // do something /// }); /// /// can be replaced by the following code: /// /// List<int> myList = ... /// await Future.forEach(myList, (int i) { /// // do something /// }); /// /// In cases where [maxTasks] is specified, package:pool is recommended. /// See: https://pub.dev/packages/pool @Deprecated('Use Future.forEach or package:pool. Will be removed in 3.0.0.') Future<Null> forEachAsync<T>(Iterable<T> iterable, AsyncAction<Null, T> action, {int maxTasks = 1}) { if (maxTasks == null || maxTasks < 1) { throw ArgumentError('maxTasks must be greater than 0, was: $maxTasks'); } if (iterable == null) { throw ArgumentError('iterable must not be null'); } if (iterable.isEmpty) return Future.value(); var completer = Completer<Null>(); var iterator = iterable.iterator; int pending = 0; bool failed = false; bool scheduleTask() { if (pending < maxTasks && iterator.moveNext()) { pending++; var item = iterator.current; scheduleMicrotask(() { var task = action(item); task.then((_) { pending--; if (failed) return; if (!scheduleTask() && pending == 0) { completer.complete(); } }).catchError((e, stack) { if (failed) return; failed = true; completer.completeError(e, stack); }); }); return true; } return false; } while (scheduleTask()) {} return completer.future; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel/web_socket_channel.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. export 'src/channel.dart'; export 'src/exception.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel/html.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library web_socket_channel.html; import 'dart:async'; import 'dart:html'; import 'dart:typed_data'; import 'package:async/async.dart'; import 'package:stream_channel/stream_channel.dart'; import 'src/channel.dart'; import 'src/exception.dart'; /// A [WebSocketChannel] that communicates using a `dart:html` [WebSocket]. class HtmlWebSocketChannel extends StreamChannelMixin implements WebSocketChannel { /// The underlying `dart:html` [WebSocket]. final WebSocket _webSocket; String get protocol => _webSocket.protocol; int get closeCode => _closeCode; int _closeCode; String get closeReason => _closeReason; String _closeReason; /// The number of bytes of data that have been queued but not yet transmitted /// to the network. int get bufferedAmount => _webSocket.bufferedAmount; /// The close code set by the local user. /// /// To ensure proper ordering, this is stored until we get a done event on /// [_controller.local.stream]. int _localCloseCode; /// The close reason set by the local user. /// /// To ensure proper ordering, this is stored until we get a done event on /// [_controller.local.stream]. String _localCloseReason; Stream get stream => _controller.foreign.stream; final _controller = StreamChannelController(sync: true, allowForeignErrors: false); WebSocketSink get sink => _sink; WebSocketSink _sink; /// Creates a new WebSocket connection. /// /// Connects to [url] using [new WebSocket] and returns a channel that can be /// used to communicate over the resulting socket. The [url] may be either a /// [String] or a [Uri]. The [protocols] parameter is the same as for /// [new WebSocket]. /// /// The [binaryType] parameter controls what type is used for binary messages /// received by this socket. It defaults to [BinaryType.list], which causes /// binary messages to be delivered as [Uint8List]s. If it's /// [BinaryType.blob], they're delivered as [Blob]s instead. HtmlWebSocketChannel.connect(url, {Iterable<String> protocols, BinaryType binaryType}) : this(WebSocket(url.toString(), protocols) ..binaryType = (binaryType ?? BinaryType.list).value); /// Creates a channel wrapping [webSocket]. HtmlWebSocketChannel(this._webSocket) { _sink = _HtmlWebSocketSink(this); if (_webSocket.readyState == WebSocket.OPEN) { _listen(); } else { // The socket API guarantees that only a single open event will be // emitted. _webSocket.onOpen.first.then((_) { _listen(); }); } // The socket API guarantees that only a single error event will be emitted, // and that once it is no open or message events will be emitted. _webSocket.onError.first.then((_) { _controller.local.sink .addError(WebSocketChannelException("WebSocket connection failed.")); _controller.local.sink.close(); }); _webSocket.onMessage.listen((event) { var data = event.data; if (data is ByteBuffer) data = data.asUint8List(); _controller.local.sink.add(data); }); // The socket API guarantees that only a single error event will be emitted, // and that once it is no other events will be emitted. _webSocket.onClose.first.then((event) { _closeCode = event.code; _closeReason = event.reason; _controller.local.sink.close(); }); } /// Pipes user events to [_webSocket]. void _listen() { _controller.local.stream.listen((message) => _webSocket.send(message), onDone: () { // On Chrome and possibly other browsers, `null` can't be passed as the // default here. The actual arity of the function call must be correct or // it will fail. if (_localCloseCode != null && _localCloseReason != null) { _webSocket.close(_localCloseCode, _localCloseReason); } else if (_localCloseCode != null) { _webSocket.close(_localCloseCode); } else { _webSocket.close(); } }); } } /// A [WebSocketSink] that tracks the close code and reason passed to [close]. class _HtmlWebSocketSink extends DelegatingStreamSink implements WebSocketSink { /// The channel to which this sink belongs. final HtmlWebSocketChannel _channel; _HtmlWebSocketSink(HtmlWebSocketChannel channel) : _channel = channel, super(channel._controller.foreign.sink); Future close([int closeCode, String closeReason]) { _channel._localCloseCode = closeCode; _channel._localCloseReason = closeReason; return super.close(); } } /// An enum for choosing what type [HtmlWebSocketChannel] emits for binary /// messages. class BinaryType { /// Tells the channel to emit binary messages as [Blob]s. static const blob = BinaryType._("blob", "blob"); /// Tells the channel to emit binary messages as [Uint8List]s. static const list = BinaryType._("list", "arraybuffer"); /// The name of the binary type, which matches its variable name. final String name; /// The value as understood by the underlying [WebSocket] API. final String value; const BinaryType._(this.name, this.value); String toString() => name; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel/status.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Status codes that are defined in the WebSocket spec. /// /// This library is intended to be imported with a prefix. /// /// ```dart /// import 'package:web_socket_channel/io.dart'; /// import 'package:web_socket_channel/status.dart' as status; /// /// main() async { /// var channel = await IOWebSocketChannel.connect("ws://localhost:1234"); /// // ... /// channel.close(status.goingAway); /// } /// ``` library web_socket_channel.status; import 'dart:core'; /// The purpose for which the connection was established has been fulfilled. const normalClosure = 1000; /// An endpoint is "going away", such as a server going down or a browser having /// navigated away from a page. const goingAway = 1001; /// An endpoint is terminating the connection due to a protocol error. const protocolError = 1002; /// An endpoint is terminating the connection because it has received a type of /// data it cannot accept. /// /// For example, an endpoint that understands only text data MAY send this if it /// receives a binary message). const unsupportedData = 1003; /// No status code was present. /// /// This **must not** be set explicitly by an endpoint. const noStatusReceived = 1005; /// The connection was closed abnormally. /// /// For example, this is used if the connection was closed without sending or /// receiving a Close control frame. /// /// This **must not** be set explicitly by an endpoint. const abnormalClosure = 1006; /// An endpoint is terminating the connection because it has received data /// within a message that was not consistent with the type of the message. /// /// For example, the endpoint may have receieved non-UTF-8 data within a text /// message. const invalidFramePayloadData = 1007; /// An endpoint is terminating the connection because it has received a message /// that violates its policy. /// /// This is a generic status code that can be returned when there is no other /// more suitable status code (such as [unsupportedData] or [messageTooBig]), or /// if there is a need to hide specific details about the policy. const policyViolation = 1008; /// An endpoint is terminating the connection because it has received a message /// that is too big for it to process. const messageTooBig = 1009; /// The client is terminating the connection because it expected the server to /// negotiate one or more extensions, but the server didn't return them in the /// response message of the WebSocket handshake. /// /// The list of extensions that are needed should appear in the close reason. /// Note that this status code is not used by the server, because it can fail /// the WebSocket handshake instead. const missingMandatoryExtension = 1010; /// The server is terminating the connection because it encountered an /// unexpected condition that prevented it from fulfilling the request. const internalServerError = 1011; /// The connection was closed due to a failure to perform a TLS handshake. /// /// For example, the server certificate may not have been verified. /// /// This **must not** be set explicitly by an endpoint. const tlsHandshakeFailed = 1015;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel/io.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library web_socket_channel.io; import 'dart:async'; import 'dart:io'; import 'package:async/async.dart'; import 'package:stream_channel/stream_channel.dart'; import 'src/channel.dart'; import 'src/exception.dart'; import 'src/sink_completer.dart'; /// A [WebSocketChannel] that communicates using a `dart:io` [WebSocket]. class IOWebSocketChannel extends StreamChannelMixin implements WebSocketChannel { /// The underlying `dart:io` [WebSocket]. /// /// If the channel was constructed with [IOWebSocketChannel.connect], this is /// `null` until the [WebSocket.connect] future completes. WebSocket _webSocket; String get protocol => _webSocket?.protocol; int get closeCode => _webSocket?.closeCode; String get closeReason => _webSocket?.closeReason; final Stream stream; final WebSocketSink sink; // TODO(nweiz): Add a compression parameter after the initial release. /// Creates a new WebSocket connection. /// /// Connects to [url] using [WebSocket.connect] and returns a channel that can /// be used to communicate over the resulting socket. The [url] may be either /// a [String] or a [Uri]. The [protocols] and [headers] parameters are the /// same as [WebSocket.connect]. /// /// [pingInterval] controls the interval for sending ping signals. If a ping /// message is not answered by a pong message from the peer, the WebSocket is /// assumed disconnected and the connection is closed with a `goingAway` code. /// When a ping signal is sent, the pong message must be received within /// [pingInterval]. It defaults to `null`, indicating that ping messages are /// disabled. /// /// If there's an error connecting, the channel's stream emits a /// [WebSocketChannelException] wrapping that error and then closes. factory IOWebSocketChannel.connect(url, {Iterable<String> protocols, Map<String, dynamic> headers, Duration pingInterval}) { var channel; var sinkCompleter = WebSocketSinkCompleter(); var stream = StreamCompleter.fromFuture(WebSocket.connect(url.toString(), headers: headers, protocols: protocols) .then((webSocket) { webSocket.pingInterval = pingInterval; channel._webSocket = webSocket; sinkCompleter.setDestinationSink(_IOWebSocketSink(webSocket)); return webSocket; }).catchError((error) => throw WebSocketChannelException.from(error))); channel = IOWebSocketChannel._withoutSocket(stream, sinkCompleter.sink); return channel; } /// Creates a channel wrapping [socket]. IOWebSocketChannel(WebSocket socket) : _webSocket = socket, stream = socket.handleError( (error) => throw WebSocketChannelException.from(error)), sink = _IOWebSocketSink(socket); /// Creates a channel without a socket. /// /// This is used with [connect] to synchronously provide a channel that later /// has a socket added. IOWebSocketChannel._withoutSocket(Stream stream, this.sink) : _webSocket = null, stream = stream.handleError( (error) => throw WebSocketChannelException.from(error)); } /// A [WebSocketSink] that forwards [close] calls to a `dart:io` [WebSocket]. class _IOWebSocketSink extends DelegatingStreamSink implements WebSocketSink { /// The underlying socket. final WebSocket _webSocket; _IOWebSocketSink(WebSocket webSocket) : _webSocket = webSocket, super(webSocket); Future close([int closeCode, String closeReason]) => _webSocket.close(closeCode, closeReason); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel/src/_connect_io.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import '../web_socket_channel.dart'; import '../io.dart'; /// Creates a new WebSocket connection. /// /// Connects to [uri] using and returns a channel that can be used to /// communicate over the resulting socket WebSocketChannel connect(Uri uri) => IOWebSocketChannel.connect(uri);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel/src/exception.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'channel.dart'; /// An exception thrown by a [WebSocketChannel]. class WebSocketChannelException implements Exception { final String message; /// The exception that caused this one, if available. final inner; WebSocketChannelException([this.message]) : inner = null; WebSocketChannelException.from(inner) : message = inner.toString(), inner = inner; String toString() => message == null ? "WebSocketChannelException" : "WebSocketChannelException: $message"; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel/src/_connect_html.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:web_socket_channel/html.dart'; import '../web_socket_channel.dart'; /// Creates a new WebSocket connection. /// /// Connects to [uri] using and returns a channel that can be used to /// communicate over the resulting socket. WebSocketChannel connect(Uri uri) => HtmlWebSocketChannel.connect(uri);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel/src/channel.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:convert' as convert; import 'package:async/async.dart'; import 'package:crypto/crypto.dart'; import 'package:stream_channel/stream_channel.dart'; import 'copy/web_socket_impl.dart'; import '_connect_api.dart' if (dart.library.io) '_connect_io.dart' if (dart.library.html) '_connect_html.dart' as platform; /// A [StreamChannel] that communicates over a WebSocket. /// /// This is implemented by classes that use `dart:io` and `dart:html`. The [new /// WebSocketChannel] constructor can also be used on any platform to connect to /// use the WebSocket protocol over a pre-existing channel. /// /// All implementations emit [WebSocketChannelException]s. These exceptions wrap /// the native exception types where possible. class WebSocketChannel extends StreamChannelMixin { /// The underlying web socket. /// /// This is essentially a copy of `dart:io`'s WebSocket implementation, with /// the IO-specific pieces factored out. final WebSocketImpl _webSocket; /// The subprotocol selected by the server. /// /// For a client socket, this is initially `null`. After the WebSocket /// connection is established the value is set to the subprotocol selected by /// the server. If no subprotocol is negotiated the value will remain `null`. String get protocol => _webSocket.protocol; /// The [close code][] set when the WebSocket connection is closed. /// /// [close code]: https://tools.ietf.org/html/rfc6455#section-7.1.5 /// /// Before the connection has been closed, this will be `null`. int get closeCode => _webSocket.closeCode; /// The [close reason][] set when the WebSocket connection is closed. /// /// [close reason]: https://tools.ietf.org/html/rfc6455#section-7.1.6 /// /// Before the connection has been closed, this will be `null`. String get closeReason => _webSocket.closeReason; Stream get stream => StreamView(_webSocket); /// The sink for sending values to the other endpoint. /// /// This supports additional arguments to [WebSocketSink.close] that provide /// the remote endpoint reasons for closing the connection. WebSocketSink get sink => WebSocketSink._(_webSocket); /// Signs a `Sec-WebSocket-Key` header sent by a WebSocket client as part of /// the [initial handshake][]. /// /// The return value should be sent back to the client in a /// `Sec-WebSocket-Accept` header. /// /// [initial handshake]: https://tools.ietf.org/html/rfc6455#section-4.2.2 static String signKey(String key) { // We use [codeUnits] here rather than UTF-8-decoding the string because // [key] is expected to be base64 encoded, and so will be pure ASCII. return convert.base64 .encode(sha1.convert((key + webSocketGUID).codeUnits).bytes); } /// Creates a new WebSocket handling messaging across an existing [channel]. /// /// This is a cross-platform constructor; it doesn't use either `dart:io` or /// `dart:html`. It's also HTTP-API-agnostic, which means that the initial /// [WebSocket handshake][] must have already been completed on the socket /// before this is called. /// /// [protocol] should be the protocol negotiated by this handshake, if any. /// /// [pingInterval] controls the interval for sending ping signals. If a ping /// message is not answered by a pong message from the peer, the WebSocket is /// assumed disconnected and the connection is closed with a `goingAway` close /// code. When a ping signal is sent, the pong message must be received within /// [pingInterval]. It defaults to `null`, indicating that ping messages are /// disabled. /// /// If this is a WebSocket server, [serverSide] should be `true` (the /// default); if it's a client, [serverSide] should be `false`. /// /// [WebSocket handshake]: https://tools.ietf.org/html/rfc6455#section-4 WebSocketChannel(StreamChannel<List<int>> channel, {String protocol, Duration pingInterval, bool serverSide = true}) : _webSocket = WebSocketImpl.fromSocket( channel.stream, channel.sink, protocol, serverSide) ..pingInterval = pingInterval; /// Creates a new WebSocket connection. /// /// Connects to [uri] using and returns a channel that can be used to /// communicate over the resulting socket. factory WebSocketChannel.connect(Uri uri) => platform.connect(uri); } /// The sink exposed by a [WebSocketChannel]. /// /// This is like a normal [StreamSink], except that it supports extra arguments /// to [close]. class WebSocketSink extends DelegatingStreamSink { final WebSocketImpl _webSocket; WebSocketSink._(WebSocketImpl webSocket) : _webSocket = webSocket, super(webSocket); /// Closes the web socket connection. /// /// [closeCode] and [closeReason] are the [close code][] and [reason][] sent /// to the remote peer, respectively. If they are omitted, the peer will see /// a "no status received" code with no reason. /// /// [close code]: https://tools.ietf.org/html/rfc6455#section-7.1.5 /// [reason]: https://tools.ietf.org/html/rfc6455#section-7.1.6 Future close([int closeCode, String closeReason]) => _webSocket.close(closeCode, closeReason); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel/src/sink_completer.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'channel.dart'; /// A [WebSocketSink] where the destination is provided later. /// /// This is like a [StreamSinkCompleter], except that it properly forwards /// paramters to [WebSocketSink.close]. class WebSocketSinkCompleter { /// The sink for this completer. /// /// When a destination sink is provided, events that have been passed to the /// sink will be forwarded to the destination. /// /// Events can be added to the sink either before or after a destination sink /// is set. final WebSocketSink sink = _CompleterSink(); /// Returns [sink] typed as a [_CompleterSink]. _CompleterSink get _sink => sink; /// Sets a sink as the destination for events from the /// [WebSocketSinkCompleter]'s [sink]. /// /// The completer's [sink] will act exactly as [destinationSink]. /// /// If the destination sink is set before events are added to [sink], further /// events are forwarded directly to [destinationSink]. /// /// If events are added to [sink] before setting the destination sink, they're /// buffered until the destination is available. /// /// A destination sink may be set at most once. void setDestinationSink(WebSocketSink destinationSink) { if (_sink._destinationSink != null) { throw StateError("Destination sink already set"); } _sink._setDestinationSink(destinationSink); } } /// [WebSocketSink] completed by [WebSocketSinkCompleter]. class _CompleterSink implements WebSocketSink { /// Controller for an intermediate sink. /// /// Created if the user adds events to this sink before the destination sink /// is set. StreamController _controller; /// Completer for [done]. /// /// Created if the user requests the [done] future before the destination sink /// is set. Completer _doneCompleter; /// Destination sink for the events added to this sink. /// /// Set when [WebSocketSinkCompleter.setDestinationSink] is called. WebSocketSink _destinationSink; /// The close code passed to [close]. int _closeCode; /// The close reason passed to [close]. String _closeReason; /// Whether events should be sent directly to [_destinationSink], as opposed /// to going through [_controller]. bool get _canSendDirectly => _controller == null && _destinationSink != null; Future get done { if (_doneCompleter != null) return _doneCompleter.future; if (_destinationSink == null) { _doneCompleter = Completer.sync(); return _doneCompleter.future; } return _destinationSink.done; } void add(event) { if (_canSendDirectly) { _destinationSink.add(event); } else { _ensureController(); _controller.add(event); } } void addError(error, [StackTrace stackTrace]) { if (_canSendDirectly) { _destinationSink.addError(error, stackTrace); } else { _ensureController(); _controller.addError(error, stackTrace); } } Future addStream(Stream stream) { if (_canSendDirectly) return _destinationSink.addStream(stream); _ensureController(); return _controller.addStream(stream, cancelOnError: false); } Future close([int closeCode, String closeReason]) { if (_canSendDirectly) { _destinationSink.close(closeCode, closeReason); } else { _closeCode = closeCode; _closeReason = closeReason; _ensureController(); _controller.close(); } return done; } /// Create [_controller] if it doesn't yet exist. void _ensureController() { if (_controller == null) _controller = StreamController(sync: true); } /// Sets the destination sink to which events from this sink will be provided. /// /// If set before the user adds events, events will be added directly to the /// destination sink. If the user adds events earlier, an intermediate sink is /// created using a stream controller, and the destination sink is linked to /// it later. void _setDestinationSink(WebSocketSink sink) { assert(_destinationSink == null); _destinationSink = sink; // If the user has already added data, it's buffered in the controller, so // we add it to the sink. if (_controller != null) { // Catch any error that may come from [addStream] or [sink.close]. They'll // be reported through [done] anyway. sink .addStream(_controller.stream) .whenComplete(() => sink.close(_closeCode, _closeReason)) .catchError((_) {}); } // If the user has already asked when the sink is done, connect the sink's // done callback to that completer. if (_doneCompleter != null) { _doneCompleter.complete(sink.done); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel/src/_connect_api.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import '../web_socket_channel.dart'; /// Creates a new WebSocket connection. /// /// Connects to [uri] using and returns a channel that can be used to /// communicate over the resulting socket. WebSocketChannel connect(Uri uri) { throw UnsupportedError('No implementation of the connect api provided'); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel/src/copy/web_socket_impl.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // The following code is copied from sdk/lib/io/websocket_impl.dart. The // "dart:io" implementation isn't used directly to support non-"dart:io" // applications. // // Because it's copied directly, only modifications necessary to support the // desired public API and to remove "dart:io" dependencies have been made. // // This is up-to-date as of sdk revision // 365f7b5a8b6ef900a5ee23913b7203569b81b175. import 'dart:async'; import 'dart:convert'; import 'dart:math'; import 'dart:typed_data'; import '../exception.dart'; import 'bytes_builder.dart'; import 'io_sink.dart'; import 'web_socket.dart'; const String webSocketGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; final _random = Random(); // Matches _WebSocketOpcode. class _WebSocketMessageType { static const int NONE = 0; static const int TEXT = 1; static const int BINARY = 2; } class _WebSocketOpcode { static const int CONTINUATION = 0; static const int TEXT = 1; static const int BINARY = 2; static const int RESERVED_3 = 3; static const int RESERVED_4 = 4; static const int RESERVED_5 = 5; static const int RESERVED_6 = 6; static const int RESERVED_7 = 7; static const int CLOSE = 8; static const int PING = 9; static const int PONG = 10; static const int RESERVED_B = 11; static const int RESERVED_C = 12; static const int RESERVED_D = 13; static const int RESERVED_E = 14; static const int RESERVED_F = 15; } /// The web socket protocol transformer handles the protocol byte stream /// which is supplied through the `handleData`. As the protocol is processed, /// it'll output frame data as either a List<int> or String. /// /// Important information about usage: Be sure you use cancelOnError, so the /// socket will be closed when the processor encounter an error. Not using it /// will lead to undefined behaviour. class _WebSocketProtocolTransformer extends StreamTransformerBase<List<int>, dynamic /*List<int>|_WebSocketPing|_WebSocketPong*/ > implements EventSink<List<int>> { static const int START = 0; static const int LEN_FIRST = 1; static const int LEN_REST = 2; static const int MASK = 3; static const int PAYLOAD = 4; static const int CLOSED = 5; static const int FAILURE = 6; static const int FIN = 0x80; static const int RSV1 = 0x40; static const int RSV2 = 0x20; static const int RSV3 = 0x10; static const int OPCODE = 0xF; int _state = START; bool _fin = false; int _opcode = -1; int _len = -1; bool _masked = false; int _remainingLenBytes = -1; int _remainingMaskingKeyBytes = 4; int _remainingPayloadBytes = -1; int _unmaskingIndex = 0; int _currentMessageType = _WebSocketMessageType.NONE; int closeCode = WebSocketStatus.NO_STATUS_RECEIVED; String closeReason = ""; EventSink<dynamic /*List<int>|_WebSocketPing|_WebSocketPong*/ > _eventSink; final bool _serverSide; final List _maskingBytes = List(4); final BytesBuilder _payload = BytesBuilder(copy: false); _WebSocketProtocolTransformer([this._serverSide = false]); Stream<dynamic /*List<int>|_WebSocketPing|_WebSocketPong*/ > bind( Stream<List<int>> stream) { return Stream.eventTransformed(stream, (EventSink eventSink) { if (_eventSink != null) { throw StateError("WebSocket transformer already used."); } _eventSink = eventSink; return this; }); } void addError(Object error, [StackTrace stackTrace]) { _eventSink.addError(error, stackTrace); } void close() { _eventSink.close(); } /// Process data received from the underlying communication channel. void add(List<int> bytes) { var buffer = bytes is Uint8List ? bytes : Uint8List.fromList(bytes); int index = 0; int lastIndex = buffer.length; if (_state == CLOSED) { throw WebSocketChannelException("Data on closed connection"); } if (_state == FAILURE) { throw WebSocketChannelException("Data on failed connection"); } while ((index < lastIndex) && _state != CLOSED && _state != FAILURE) { int byte = buffer[index]; if (_state <= LEN_REST) { if (_state == START) { _fin = (byte & FIN) != 0; if ((byte & (RSV2 | RSV3)) != 0) { // The RSV2, RSV3 bits must both be zero. throw WebSocketChannelException("Protocol error"); } _opcode = (byte & OPCODE); if (_opcode <= _WebSocketOpcode.BINARY) { if (_opcode == _WebSocketOpcode.CONTINUATION) { if (_currentMessageType == _WebSocketMessageType.NONE) { throw WebSocketChannelException("Protocol error"); } } else { assert(_opcode == _WebSocketOpcode.TEXT || _opcode == _WebSocketOpcode.BINARY); if (_currentMessageType != _WebSocketMessageType.NONE) { throw WebSocketChannelException("Protocol error"); } _currentMessageType = _opcode; } } else if (_opcode >= _WebSocketOpcode.CLOSE && _opcode <= _WebSocketOpcode.PONG) { // Control frames cannot be fragmented. if (!_fin) throw WebSocketChannelException("Protocol error"); } else { throw WebSocketChannelException("Protocol error"); } _state = LEN_FIRST; } else if (_state == LEN_FIRST) { _masked = (byte & 0x80) != 0; _len = byte & 0x7F; if (_isControlFrame() && _len > 125) { throw WebSocketChannelException("Protocol error"); } if (_len == 126) { _len = 0; _remainingLenBytes = 2; _state = LEN_REST; } else if (_len == 127) { _len = 0; _remainingLenBytes = 8; _state = LEN_REST; } else { assert(_len < 126); _lengthDone(); } } else { assert(_state == LEN_REST); _len = _len << 8 | byte; _remainingLenBytes--; if (_remainingLenBytes == 0) { _lengthDone(); } } } else { if (_state == MASK) { _maskingBytes[4 - _remainingMaskingKeyBytes--] = byte; if (_remainingMaskingKeyBytes == 0) { _maskDone(); } } else { assert(_state == PAYLOAD); // The payload is not handled one byte at a time but in blocks. int payloadLength = min(lastIndex - index, _remainingPayloadBytes); _remainingPayloadBytes -= payloadLength; // Unmask payload if masked. if (_masked) { _unmask(index, payloadLength, buffer); } // Control frame and data frame share _payloads. _payload.add(Uint8List.view(buffer.buffer, index, payloadLength)); index += payloadLength; if (_isControlFrame()) { if (_remainingPayloadBytes == 0) _controlFrameEnd(); } else { if (_currentMessageType != _WebSocketMessageType.TEXT && _currentMessageType != _WebSocketMessageType.BINARY) { throw WebSocketChannelException("Protocol error"); } if (_remainingPayloadBytes == 0) _messageFrameEnd(); } // Hack - as we always do index++ below. index--; } } // Move to the next byte. index++; } } void _unmask(int index, int length, Uint8List buffer) { const int BLOCK_SIZE = 16; // Skip Int32x4-version if message is small. if (length >= BLOCK_SIZE) { // Start by aligning to 16 bytes. final int startOffset = BLOCK_SIZE - (index & 15); final int end = index + startOffset; for (int i = index; i < end; i++) { buffer[i] ^= _maskingBytes[_unmaskingIndex++ & 3]; } index += startOffset; length -= startOffset; final int blockCount = length ~/ BLOCK_SIZE; if (blockCount > 0) { // Create mask block. int mask = 0; for (int i = 3; i >= 0; i--) { mask = (mask << 8) | _maskingBytes[(_unmaskingIndex + i) & 3]; } Int32x4 blockMask = Int32x4(mask, mask, mask, mask); Int32x4List blockBuffer = Int32x4List.view(buffer.buffer, index, blockCount); for (int i = 0; i < blockBuffer.length; i++) { blockBuffer[i] ^= blockMask; } final int bytes = blockCount * BLOCK_SIZE; index += bytes; length -= bytes; } } // Handle end. final int end = index + length; for (int i = index; i < end; i++) { buffer[i] ^= _maskingBytes[_unmaskingIndex++ & 3]; } } void _lengthDone() { if (_masked) { if (!_serverSide) { throw WebSocketChannelException("Received masked frame from server"); } _state = MASK; } else { if (_serverSide) { throw WebSocketChannelException("Received unmasked frame from client"); } _remainingPayloadBytes = _len; _startPayload(); } } void _maskDone() { _remainingPayloadBytes = _len; _startPayload(); } void _startPayload() { // If there is no actual payload perform perform callbacks without // going through the PAYLOAD state. if (_remainingPayloadBytes == 0) { if (_isControlFrame()) { switch (_opcode) { case _WebSocketOpcode.CLOSE: _state = CLOSED; _eventSink.close(); break; case _WebSocketOpcode.PING: _eventSink.add(_WebSocketPing()); break; case _WebSocketOpcode.PONG: _eventSink.add(_WebSocketPong()); break; } _prepareForNextFrame(); } else { _messageFrameEnd(); } } else { _state = PAYLOAD; } } void _messageFrameEnd() { if (_fin) { var bytes = _payload.takeBytes(); switch (_currentMessageType) { case _WebSocketMessageType.TEXT: _eventSink.add(utf8.decode(bytes)); break; case _WebSocketMessageType.BINARY: _eventSink.add(bytes); break; } _currentMessageType = _WebSocketMessageType.NONE; } _prepareForNextFrame(); } void _controlFrameEnd() { switch (_opcode) { case _WebSocketOpcode.CLOSE: closeCode = WebSocketStatus.NO_STATUS_RECEIVED; var payload = _payload.takeBytes(); if (payload.isNotEmpty) { if (payload.length == 1) { throw WebSocketChannelException("Protocol error"); } closeCode = payload[0] << 8 | payload[1]; if (closeCode == WebSocketStatus.NO_STATUS_RECEIVED) { throw WebSocketChannelException("Protocol error"); } if (payload.length > 2) { closeReason = utf8.decode(payload.sublist(2)); } } _state = CLOSED; _eventSink.close(); break; case _WebSocketOpcode.PING: _eventSink.add(_WebSocketPing(_payload.takeBytes())); break; case _WebSocketOpcode.PONG: _eventSink.add(_WebSocketPong(_payload.takeBytes())); break; } _prepareForNextFrame(); } bool _isControlFrame() { return _opcode == _WebSocketOpcode.CLOSE || _opcode == _WebSocketOpcode.PING || _opcode == _WebSocketOpcode.PONG; } void _prepareForNextFrame() { if (_state != CLOSED && _state != FAILURE) _state = START; _fin = false; _opcode = -1; _len = -1; _remainingLenBytes = -1; _remainingMaskingKeyBytes = 4; _remainingPayloadBytes = -1; _unmaskingIndex = 0; } } class _WebSocketPing { final List<int> payload; _WebSocketPing([this.payload]); } class _WebSocketPong { final List<int> payload; _WebSocketPong([this.payload]); } // TODO(ajohnsen): Make this transformer reusable. class _WebSocketOutgoingTransformer extends StreamTransformerBase<dynamic, List<int>> implements EventSink { final WebSocketImpl webSocket; EventSink<List<int>> _eventSink; _WebSocketOutgoingTransformer(this.webSocket); Stream<List<int>> bind(Stream stream) { return Stream<List<int>>.eventTransformed(stream, (EventSink<List<int>> eventSink) { if (_eventSink != null) { throw StateError("WebSocket transformer already used"); } _eventSink = eventSink; return this; }); } void add(message) { if (message is _WebSocketPong) { addFrame(_WebSocketOpcode.PONG, message.payload); return; } if (message is _WebSocketPing) { addFrame(_WebSocketOpcode.PING, message.payload); return; } List<int> data; int opcode; if (message != null) { if (message is String) { opcode = _WebSocketOpcode.TEXT; data = utf8.encode(message); } else if (message is List<int>) { opcode = _WebSocketOpcode.BINARY; data = message; } else { throw ArgumentError(message); } } else { opcode = _WebSocketOpcode.TEXT; } addFrame(opcode, data); } void addError(Object error, [StackTrace stackTrace]) { _eventSink.addError(error, stackTrace); } void close() { int code = webSocket._outCloseCode; String reason = webSocket._outCloseReason; List<int> data; if (code != null) { data = List<int>(); data.add((code >> 8) & 0xFF); data.add(code & 0xFF); if (reason != null) { data.addAll(utf8.encode(reason)); } } addFrame(_WebSocketOpcode.CLOSE, data); _eventSink.close(); } void addFrame(int opcode, List<int> data) { createFrame( opcode, data, webSocket._serverSide, // Logic around _deflateHelper was removed here, since ther ewill never // be a deflate helper for a cross-platform WebSocket client. false) .forEach((e) { _eventSink.add(e); }); } static Iterable<List<int>> createFrame( int opcode, List<int> data, bool serverSide, bool compressed) { bool mask = !serverSide; // Masking not implemented for server. int dataLength = data == null ? 0 : data.length; // Determine the header size. int headerSize = (mask) ? 6 : 2; if (dataLength > 65535) { headerSize += 8; } else if (dataLength > 125) { headerSize += 2; } Uint8List header = Uint8List(headerSize); int index = 0; // Set FIN and opcode. var hoc = _WebSocketProtocolTransformer.FIN | (compressed ? _WebSocketProtocolTransformer.RSV1 : 0) | (opcode & _WebSocketProtocolTransformer.OPCODE); header[index++] = hoc; // Determine size and position of length field. int lengthBytes = 1; if (dataLength > 65535) { header[index++] = 127; lengthBytes = 8; } else if (dataLength > 125) { header[index++] = 126; lengthBytes = 2; } // Write the length in network byte order into the header. for (int i = 0; i < lengthBytes; i++) { header[index++] = dataLength >> (((lengthBytes - 1) - i) * 8) & 0xFF; } if (mask) { header[1] |= 1 << 7; var maskBytes = [ _random.nextInt(256), _random.nextInt(256), _random.nextInt(256), _random.nextInt(256) ]; header.setRange(index, index + 4, maskBytes); index += 4; if (data != null) { Uint8List list; // If this is a text message just do the masking inside the // encoded data. if (opcode == _WebSocketOpcode.TEXT && data is Uint8List) { list = data; } else { if (data is Uint8List) { list = Uint8List.fromList(data); } else { list = Uint8List(data.length); for (int i = 0; i < data.length; i++) { if (data[i] < 0 || 255 < data[i]) { throw ArgumentError("List element is not a byte value " "(value ${data[i]} at index $i)"); } list[i] = data[i]; } } } const int BLOCK_SIZE = 16; int blockCount = list.length ~/ BLOCK_SIZE; if (blockCount > 0) { // Create mask block. int mask = 0; for (int i = 3; i >= 0; i--) { mask = (mask << 8) | maskBytes[i]; } Int32x4 blockMask = Int32x4(mask, mask, mask, mask); Int32x4List blockBuffer = Int32x4List.view(list.buffer, 0, blockCount); for (int i = 0; i < blockBuffer.length; i++) { blockBuffer[i] ^= blockMask; } } // Handle end. for (int i = blockCount * BLOCK_SIZE; i < list.length; i++) { list[i] ^= maskBytes[i & 3]; } data = list; } } assert(index == headerSize); if (data == null) { return [header]; } else { return [header, data]; } } } class _WebSocketConsumer implements StreamConsumer { final WebSocketImpl webSocket; final StreamSink<List<int>> sink; StreamController _controller; StreamSubscription _subscription; bool _issuedPause = false; bool _closed = false; final Completer _closeCompleter = Completer<WebSocketImpl>(); Completer _completer; _WebSocketConsumer(this.webSocket, this.sink); void _onListen() { if (_subscription != null) { _subscription.cancel(); } } void _onPause() { if (_subscription != null) { _subscription.pause(); } else { _issuedPause = true; } } void _onResume() { if (_subscription != null) { _subscription.resume(); } else { _issuedPause = false; } } void _cancel() { if (_subscription != null) { var subscription = _subscription; _subscription = null; subscription.cancel(); } } _ensureController() { if (_controller != null) return; _controller = StreamController( sync: true, onPause: _onPause, onResume: _onResume, onCancel: _onListen); var stream = _WebSocketOutgoingTransformer(webSocket).bind(_controller.stream); sink.addStream(stream).then((_) { _done(); _closeCompleter.complete(webSocket); }, onError: (error, StackTrace stackTrace) { _closed = true; _cancel(); if (error is ArgumentError) { if (!_done(error, stackTrace)) { _closeCompleter.completeError(error, stackTrace); } } else { _done(); _closeCompleter.complete(webSocket); } }); } bool _done([error, StackTrace stackTrace]) { if (_completer == null) return false; if (error != null) { _completer.completeError(error, stackTrace); } else { _completer.complete(webSocket); } _completer = null; return true; } Future addStream(var stream) { if (_closed) { stream.listen(null).cancel(); return Future.value(webSocket); } _ensureController(); _completer = Completer(); _subscription = stream.listen((data) { _controller.add(data); }, onDone: _done, onError: _done, cancelOnError: true); if (_issuedPause) { _subscription.pause(); _issuedPause = false; } return _completer.future; } Future close() { _ensureController(); Future closeSocket() { return sink.close().catchError((_) {}).then((_) => webSocket); } _controller.close(); return _closeCompleter.future.then((_) => closeSocket()); } void add(data) { if (_closed) return; _ensureController(); _controller.add(data); } void closeSocket() { _closed = true; _cancel(); close(); } } class WebSocketImpl extends Stream with _ServiceObject implements StreamSink { // Use default Map so we keep order. static final Map<int, WebSocketImpl> _webSockets = Map<int, WebSocketImpl>(); static const int DEFAULT_WINDOW_BITS = 15; static const String PER_MESSAGE_DEFLATE = "permessage-deflate"; final String protocol; StreamController _controller; StreamSubscription _subscription; StreamSink _sink; final bool _serverSide; int _readyState = WebSocket.CONNECTING; bool _writeClosed = false; int _closeCode; String _closeReason; Duration _pingInterval; Timer _pingTimer; _WebSocketConsumer _consumer; int _outCloseCode; String _outCloseReason; Timer _closeTimer; WebSocketImpl.fromSocket( Stream<List<int>> stream, StreamSink<List<int>> sink, this.protocol, [this._serverSide = false]) { _consumer = _WebSocketConsumer(this, sink); _sink = StreamSinkImpl(_consumer); _readyState = WebSocket.OPEN; var transformer = _WebSocketProtocolTransformer(_serverSide); _subscription = transformer.bind(stream).listen((data) { if (data is _WebSocketPing) { if (!_writeClosed) _consumer.add(_WebSocketPong(data.payload)); } else if (data is _WebSocketPong) { // Simply set pingInterval, as it'll cancel any timers. pingInterval = _pingInterval; } else { _controller.add(data); } }, onError: (error, stackTrace) { if (_closeTimer != null) _closeTimer.cancel(); if (error is FormatException) { _close(WebSocketStatus.INVALID_FRAME_PAYLOAD_DATA); } else { _close(WebSocketStatus.PROTOCOL_ERROR); } // An error happened, set the close code set above. _closeCode = _outCloseCode; _closeReason = _outCloseReason; _controller.close(); }, onDone: () { if (_closeTimer != null) _closeTimer.cancel(); if (_readyState == WebSocket.OPEN) { _readyState = WebSocket.CLOSING; if (!_isReservedStatusCode(transformer.closeCode)) { _close(transformer.closeCode, transformer.closeReason); } else { _close(); } _readyState = WebSocket.CLOSED; } // Protocol close, use close code from transformer. _closeCode = transformer.closeCode; _closeReason = transformer.closeReason; _controller.close(); }, cancelOnError: true); _subscription.pause(); _controller = StreamController( sync: true, onListen: () => _subscription.resume(), onCancel: () { _subscription.cancel(); _subscription = null; }, onPause: _subscription.pause, onResume: _subscription.resume); _webSockets[_serviceId] = this; } StreamSubscription listen(void onData(message), {Function onError, void onDone(), bool cancelOnError}) { return _controller.stream.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); } Duration get pingInterval => _pingInterval; set pingInterval(Duration interval) { if (_writeClosed) return; if (_pingTimer != null) _pingTimer.cancel(); _pingInterval = interval; if (_pingInterval == null) return; _pingTimer = Timer(_pingInterval, () { if (_writeClosed) return; _consumer.add(_WebSocketPing()); _pingTimer = Timer(_pingInterval, () { // No pong received. _close(WebSocketStatus.GOING_AWAY); }); }); } int get readyState => _readyState; String get extensions => null; int get closeCode => _closeCode; String get closeReason => _closeReason; void add(data) { _sink.add(data); } void addError(error, [StackTrace stackTrace]) { _sink.addError(error, stackTrace); } Future addStream(Stream stream) => _sink.addStream(stream); Future get done => _sink.done; Future close([int code, String reason]) { if (_isReservedStatusCode(code)) { throw WebSocketChannelException("Reserved status code $code"); } if (_outCloseCode == null) { _outCloseCode = code; _outCloseReason = reason; } if (!_controller.isClosed) { // If a close has not yet been received from the other end then // 1) make sure to listen on the stream so the close frame will be // processed if received. // 2) set a timer terminate the connection if a close frame is // not received. if (!_controller.hasListener && _subscription != null) { _controller.stream.drain().catchError((_) => {}); } if (_closeTimer == null) { // When closing the web-socket, we no longer accept data. _closeTimer = Timer(const Duration(seconds: 5), () { // Reuse code and reason from the local close. _closeCode = _outCloseCode; _closeReason = _outCloseReason; if (_subscription != null) _subscription.cancel(); _controller.close(); _webSockets.remove(_serviceId); }); } } return _sink.close(); } void _close([int code, String reason]) { if (_writeClosed) return; if (_outCloseCode == null) { _outCloseCode = code; _outCloseReason = reason; } _writeClosed = true; _consumer.closeSocket(); _webSockets.remove(_serviceId); } // The _toJSON, _serviceTypePath, and _serviceTypeName methods have been // deleted for web_socket_channel. The methods were unused in WebSocket code // and produced warnings. static bool _isReservedStatusCode(int code) { return code != null && (code < WebSocketStatus.NORMAL_CLOSURE || code == WebSocketStatus.RESERVED_1004 || code == WebSocketStatus.NO_STATUS_RECEIVED || code == WebSocketStatus.ABNORMAL_CLOSURE || (code > WebSocketStatus.INTERNAL_SERVER_ERROR && code < WebSocketStatus.RESERVED_1015) || (code >= WebSocketStatus.RESERVED_1015 && code < 3000)); } } // The following code is from sdk/lib/io/service_object.dart. int _nextServiceId = 1; // TODO(ajohnsen): Use other way of getting a uniq id. abstract class _ServiceObject { int __serviceId = 0; int get _serviceId { if (__serviceId == 0) __serviceId = _nextServiceId++; return __serviceId; } // The _toJSON, _servicePath, _serviceTypePath, _serviceTypeName, and // _serviceType methods have been deleted for http_parser. The methods were // unused in WebSocket code and produced warnings. }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel/src/copy/bytes_builder.dart
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // This is a copy of "dart:io"'s BytesBuilder implementation, from // sdk/lib/io/bytes_builder.dart. It's copied here to make it available to // non-"dart:io" applications (issue 18348). // // Because it's copied directly, there are no modifications from the original. // // This is up-to-date as of sdk revision // 365f7b5a8b6ef900a5ee23913b7203569b81b175. import 'dart:typed_data'; /// Builds a list of bytes, allowing bytes and lists of bytes to be added at the /// end. /// /// Used to efficiently collect bytes and lists of bytes. abstract class BytesBuilder { /// Construct a new empty [BytesBuilder]. /// /// If [copy] is true, the data is always copied when added to the list. If /// it [copy] is false, the data is only copied if needed. That means that if /// the lists are changed after added to the [BytesBuilder], it may effect the /// output. Default is `true`. factory BytesBuilder({bool copy = true}) { if (copy) { return _CopyingBytesBuilder(); } else { return _BytesBuilder(); } } /// Appends [bytes] to the current contents of the builder. /// /// Each value of [bytes] will be bit-representation truncated to the range /// 0 .. 255. void add(List<int> bytes); /// Append [byte] to the current contents of the builder. /// /// The [byte] will be bit-representation truncated to the range 0 .. 255. void addByte(int byte); /// Returns the contents of `this` and clears `this`. /// /// The list returned is a view of the internal buffer, limited to the /// [length]. Uint8List takeBytes(); /// Returns a copy of the current contents of the builder. /// /// Leaves the contents of the builder intact. Uint8List toBytes(); /// The number of bytes in the builder. int get length; /// Returns `true` if the buffer is empty. bool get isEmpty; /// Returns `true` if the buffer is not empty. bool get isNotEmpty; /// Clear the contents of the builder. void clear(); } class _CopyingBytesBuilder implements BytesBuilder { // Start with 1024 bytes. static const int _INIT_SIZE = 1024; static final _emptyList = Uint8List(0); int _length = 0; Uint8List _buffer; _CopyingBytesBuilder([int initialCapacity = 0]) : _buffer = (initialCapacity <= 0) ? _emptyList : Uint8List(_pow2roundup(initialCapacity)); void add(List<int> bytes) { int bytesLength = bytes.length; if (bytesLength == 0) return; int required = _length + bytesLength; if (_buffer.length < required) { _grow(required); } assert(_buffer.length >= required); if (bytes is Uint8List) { _buffer.setRange(_length, required, bytes); } else { for (int i = 0; i < bytesLength; i++) { _buffer[_length + i] = bytes[i]; } } _length = required; } void addByte(int byte) { if (_buffer.length == _length) { // The grow algorithm always at least doubles. // If we added one to _length it would quadruple unnecessarily. _grow(_length); } assert(_buffer.length > _length); _buffer[_length] = byte; _length++; } void _grow(int required) { // We will create a list in the range of 2-4 times larger than // required. int newSize = required * 2; if (newSize < _INIT_SIZE) { newSize = _INIT_SIZE; } else { newSize = _pow2roundup(newSize); } var newBuffer = Uint8List(newSize); newBuffer.setRange(0, _buffer.length, _buffer); _buffer = newBuffer; } Uint8List takeBytes() { if (_length == 0) return _emptyList; var buffer = Uint8List.view(_buffer.buffer, 0, _length); clear(); return buffer; } Uint8List toBytes() { if (_length == 0) return _emptyList; return Uint8List.fromList(Uint8List.view(_buffer.buffer, 0, _length)); } int get length => _length; bool get isEmpty => _length == 0; bool get isNotEmpty => _length != 0; void clear() { _length = 0; _buffer = _emptyList; } static int _pow2roundup(int x) { assert(x > 0); --x; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x + 1; } } class _BytesBuilder implements BytesBuilder { int _length = 0; final List<Uint8List> _chunks = []; void add(List<int> bytes) { Uint8List typedBytes; if (bytes is Uint8List) { typedBytes = bytes; } else { typedBytes = Uint8List.fromList(bytes); } _chunks.add(typedBytes); _length += typedBytes.length; } void addByte(int byte) { _chunks.add(Uint8List(1)..[0] = byte); _length++; } Uint8List takeBytes() { if (_length == 0) return _CopyingBytesBuilder._emptyList; if (_chunks.length == 1) { var buffer = _chunks[0]; clear(); return buffer; } var buffer = Uint8List(_length); int offset = 0; for (var chunk in _chunks) { buffer.setRange(offset, offset + chunk.length, chunk); offset += chunk.length; } clear(); return buffer; } Uint8List toBytes() { if (_length == 0) return _CopyingBytesBuilder._emptyList; var buffer = Uint8List(_length); int offset = 0; for (var chunk in _chunks) { buffer.setRange(offset, offset + chunk.length, chunk); offset += chunk.length; } return buffer; } int get length => _length; bool get isEmpty => _length == 0; bool get isNotEmpty => _length != 0; void clear() { _length = 0; _chunks.clear(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel/src/copy/io_sink.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // The following code is copied from sdk/lib/io/io_sink.dart. The "dart:io" // implementation isn't used directly to support non-"dart:io" applications. // // Because it's copied directly, only modifications necessary to support the // desired public API and to remove "dart:io" dependencies have been made. // // This is up-to-date as of sdk revision // 365f7b5a8b6ef900a5ee23913b7203569b81b175. import 'dart:async'; class StreamSinkImpl<T> implements StreamSink<T> { final StreamConsumer<T> _target; final Completer _doneCompleter = Completer(); StreamController<T> _controllerInstance; Completer _controllerCompleter; bool _isClosed = false; bool _isBound = false; bool _hasError = false; StreamSinkImpl(this._target); // The _reportClosedSink method has been deleted for web_socket_channel. This // method did nothing but print to stderr, which is unavailable here. void add(T data) { if (_isClosed) { return; } _controller.add(data); } void addError(error, [StackTrace stackTrace]) { if (_isClosed) { return; } _controller.addError(error, stackTrace); } Future addStream(Stream<T> stream) { if (_isBound) { throw StateError("StreamSink is already bound to a stream"); } if (_hasError) return done; _isBound = true; var future = _controllerCompleter == null ? _target.addStream(stream) : _controllerCompleter.future.then((_) => _target.addStream(stream)); _controllerInstance?.close(); // Wait for any pending events in [_controller] to be dispatched before // adding [stream]. return future.whenComplete(() { _isBound = false; }); } Future flush() { if (_isBound) { throw StateError("StreamSink is bound to a stream"); } if (_controllerInstance == null) return Future.value(this); // Adding an empty stream-controller will return a future that will complete // when all data is done. _isBound = true; var future = _controllerCompleter.future; _controllerInstance.close(); return future.whenComplete(() { _isBound = false; }); } Future close() { if (_isBound) { throw StateError("StreamSink is bound to a stream"); } if (!_isClosed) { _isClosed = true; if (_controllerInstance != null) { _controllerInstance.close(); } else { _closeTarget(); } } return done; } void _closeTarget() { _target.close().then(_completeDoneValue, onError: _completeDoneError); } Future get done => _doneCompleter.future; void _completeDoneValue(value) { if (!_doneCompleter.isCompleted) { _doneCompleter.complete(value); } } void _completeDoneError(error, StackTrace stackTrace) { if (!_doneCompleter.isCompleted) { _hasError = true; _doneCompleter.completeError(error, stackTrace); } } StreamController<T> get _controller { if (_isBound) { throw StateError("StreamSink is bound to a stream"); } if (_isClosed) { throw StateError("StreamSink is closed"); } if (_controllerInstance == null) { _controllerInstance = StreamController<T>(sync: true); _controllerCompleter = Completer(); _target.addStream(_controller.stream).then((_) { if (_isBound) { // A new stream takes over - forward values to that stream. _controllerCompleter.complete(this); _controllerCompleter = null; _controllerInstance = null; } else { // No new stream, .close was called. Close _target. _closeTarget(); } }, onError: (error, stackTrace) { if (_isBound) { // A new stream takes over - forward errors to that stream. _controllerCompleter.completeError(error, stackTrace); _controllerCompleter = null; _controllerInstance = null; } else { // No new stream. No need to close target, as it has already // failed. _completeDoneError(error, stackTrace); } }); } return _controllerInstance; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/web_socket_channel/src/copy/web_socket.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // The following code is copied from sdk/lib/io/websocket.dart. The "dart:io" // implementation isn't used directly to support non-"dart:io" applications. // // Because it's copied directly, only modifications necessary to support the // desired public API and to remove "dart:io" dependencies have been made. // // This is up-to-date as of sdk revision // 365f7b5a8b6ef900a5ee23913b7203569b81b175. /// Web socket status codes used when closing a web socket connection. abstract class WebSocketStatus { static const int NORMAL_CLOSURE = 1000; static const int GOING_AWAY = 1001; static const int PROTOCOL_ERROR = 1002; static const int UNSUPPORTED_DATA = 1003; static const int RESERVED_1004 = 1004; static const int NO_STATUS_RECEIVED = 1005; static const int ABNORMAL_CLOSURE = 1006; static const int INVALID_FRAME_PAYLOAD_DATA = 1007; static const int POLICY_VIOLATION = 1008; static const int MESSAGE_TOO_BIG = 1009; static const int MISSING_MANDATORY_EXTENSION = 1010; static const int INTERNAL_SERVER_ERROR = 1011; static const int RESERVED_1015 = 1015; } abstract class WebSocket { /// Possible states of the connection. static const int CONNECTING = 0; static const int OPEN = 1; static const int CLOSING = 2; static const int CLOSED = 3; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/client.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:build_daemon/data/build_target.dart'; import 'package:built_value/serializer.dart'; import 'package:web_socket_channel/io.dart'; import 'constants.dart'; import 'data/build_request.dart'; import 'data/build_status.dart'; import 'data/build_target_request.dart'; import 'data/serializers.dart'; import 'data/server_log.dart'; import 'data/shutdown_notification.dart'; import 'src/file_wait.dart'; Future<int> _existingPort(String workingDirectory) async { var portFile = File(portFilePath(workingDirectory)); if (!await waitForFile(portFile)) throw MissingPortFile(); return int.parse(portFile.readAsStringSync()); } Future<void> _handleDaemonStartup( Process process, void Function(ServerLog) logHandler, ) async { process.stderr .transform(utf8.decoder) .transform(const LineSplitter()) .listen((line) { logHandler(ServerLog((b) => b ..level = Level.SEVERE ..message = line)); }); var stdout = process.stdout .transform(utf8.decoder) .transform(const LineSplitter()) .asBroadcastStream(); // The daemon may log critical information prior to it successfully // starting. Capture this data and forward to the logHandler. // // Whenever we see a `logStartMarker` we will parse everything between that // and the `logEndMarker` as a `ServerLog`. Everything else is considered a // normal INFO level log. StringBuffer nextLogRecord; var sub = stdout.where((line) => !_isActionMessage(line)).listen((line) { if (nextLogRecord != null) { if (line == logEndMarker) { try { logHandler(serializers .deserialize(jsonDecode(nextLogRecord.toString())) as ServerLog); } catch (e, s) { logHandler(ServerLog((builder) => builder ..message = 'Failed to read log message:\n$nextLogRecord' ..level = Level.SEVERE ..error = '$e' ..stackTrace = '$s')); } nextLogRecord = null; } else { nextLogRecord.writeln(line); } } else if (line == logStartMarker) { nextLogRecord = StringBuffer(); } else { logHandler(ServerLog((b) => b ..level = Level.INFO ..message = line)); } }); var daemonAction = await stdout.firstWhere(_isActionMessage, orElse: () => null); if (daemonAction == null) { throw StateError('Unable to start build daemon.'); } else if (daemonAction == versionSkew) { throw VersionSkew(); } else if (daemonAction == optionsSkew) { throw OptionsSkew(); } await sub.cancel(); } bool _isActionMessage(String line) => line == versionSkew || line == readyToConnectLog || line == optionsSkew; /// A client of the build daemon. /// /// Handles starting and connecting to the build daemon. /// /// Example: /// https://pub.dev/packages/build_daemon#-example-tab- class BuildDaemonClient { final _buildResults = StreamController<BuildResults>.broadcast(); final _shutdownNotifications = StreamController<ShutdownNotification>.broadcast(); final Serializers _serializers; IOWebSocketChannel _channel; BuildDaemonClient._( int port, this._serializers, void Function(ServerLog) logHandler, ) { _channel = IOWebSocketChannel.connect('ws://localhost:$port') ..stream.listen((data) { var message = _serializers.deserialize(jsonDecode(data as String)); if (message is ServerLog) { logHandler(message); } else if (message is BuildResults) { _buildResults.add(message); } else if (message is ShutdownNotification) { _shutdownNotifications.add(message); } else { // In practice we should never reach this state due to the // deserialize call. throw StateError( 'Unexpected message from the Dart Build Daemon\n $message'); } }) // TODO(grouma) - Implement proper error handling. .onError(print); } Stream<BuildResults> get buildResults => _buildResults.stream; Stream<ShutdownNotification> get shutdownNotifications => _shutdownNotifications.stream; Future<void> get finished async => await _channel.sink.done; /// Registers a build target to be built upon any file change. void registerBuildTarget(BuildTarget target) => _channel.sink.add(jsonEncode( _serializers.serialize(BuildTargetRequest((b) => b..target = target)))); /// Builds all registered targets, including those not from this client. /// /// Note this will wait for any ongoing build to finish before starting a new /// one. void startBuild() { var request = BuildRequest(); _channel.sink.add(jsonEncode(_serializers.serialize(request))); } Future<void> close() => _channel.sink.close(); /// Connects to the current daemon instance. /// /// If one is not running, a new daemon instance will be started. static Future<BuildDaemonClient> connect( String workingDirectory, List<String> daemonCommand, { Serializers serializersOverride, void Function(ServerLog) logHandler, bool includeParentEnvironment, Map<String, String> environment, BuildMode buildMode, }) async { logHandler ??= (_) {}; includeParentEnvironment ??= true; buildMode ??= BuildMode.Auto; var daemonSerializers = serializersOverride ?? serializers; var daemonArgs = daemonCommand.sublist(1) ..add('--$buildModeFlag=$buildMode'); var process = await Process.start( daemonCommand.first, daemonArgs, mode: ProcessStartMode.detachedWithStdio, workingDirectory: workingDirectory, environment: environment, includeParentEnvironment: includeParentEnvironment, ); await _handleDaemonStartup(process, logHandler); return BuildDaemonClient._( await _existingPort(workingDirectory), daemonSerializers, logHandler); } } /// Thrown when the port file for the running daemon instance can't be found. class MissingPortFile implements Exception {} /// Thrown if the client requests conflicting options with the current daemon /// instance. class OptionsSkew implements Exception {} /// Thrown if the current daemon instance version does not match that of the /// client. class VersionSkew implements Exception {}
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/daemon.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:built_value/serializer.dart'; import 'package:pedantic/pedantic.dart'; import 'package:watcher/watcher.dart'; import 'change_provider.dart'; import 'constants.dart'; import 'daemon_builder.dart'; import 'data/build_target.dart'; import 'src/file_wait.dart'; import 'src/server.dart'; /// The long running daemon process. /// /// Obtains a file lock to ensure a single instance and writes various status /// files to be used by clients for connection. /// /// Also starts a [Server] to listen for build target registration and event /// notification. class Daemon { final String _workingDirectory; final RandomAccessFile _lock; final _doneCompleter = Completer(); Server _server; StreamSubscription _sub; Daemon(String workingDirectory) : _workingDirectory = workingDirectory, _lock = _tryGetLock(workingDirectory); Future<void> get onDone => _doneCompleter.future; Future<void> stop({String message, int failureType}) => _server.stop(message: message, failureType: failureType); bool get hasLock => _lock != null; /// Returns the current version of the running build daemon. /// /// Null if one isn't running. Future<String> runningVersion() async { var versionFile = File(versionFilePath(_workingDirectory)); if (!await waitForFile(versionFile)) return null; return versionFile.readAsStringSync(); } /// Returns the current options of the running build daemon. /// /// Null if one isn't running. Future<Set<String>> currentOptions() async { var optionsFile = File(optionsFilePath(_workingDirectory)); if (!await waitForFile(optionsFile)) return <String>{}; return optionsFile.readAsLinesSync().toSet(); } Future<void> start( Set<String> options, DaemonBuilder builder, ChangeProvider changeProvider, { Serializers serializersOverride, bool Function(BuildTarget, Iterable<WatchEvent>) shouldBuild, Duration timeout = const Duration(seconds: 30), }) async { if (_server != null || _lock == null) return; _handleGracefulExit(); _createVersionFile(); _createOptionsFile(options); _server = Server( builder, timeout, changeProvider, serializersOverride: serializersOverride, shouldBuild: shouldBuild, ); var port = await _server.listen(); _createPortFile(port); unawaited(_server.onDone.then((_) async { await _cleanUp(); })); } Future<void> _cleanUp() async { await _server?.stop(); await _sub?.cancel(); // We need to close the lock prior to deleting the file. _lock?.closeSync(); var workspace = Directory(daemonWorkspace(_workingDirectory)); if (workspace.existsSync()) { workspace.deleteSync(recursive: true); } if (!_doneCompleter.isCompleted) _doneCompleter.complete(); } void _createPortFile(int port) => File(portFilePath(_workingDirectory)).writeAsStringSync('$port'); void _createVersionFile() => File(versionFilePath(_workingDirectory)) .writeAsStringSync(currentVersion); void _createOptionsFile(Set<String> options) => File(optionsFilePath(_workingDirectory)) .writeAsStringSync(options.toList().join('\n')); void _handleGracefulExit() { var cancelCount = 0; _sub = ProcessSignal.sigint.watch().listen((signal) async { if (signal == ProcessSignal.sigint) { cancelCount++; await _server.stop(); if (cancelCount > 1) exit(1); } }); } } RandomAccessFile _tryGetLock(String workingDirectory) { try { _createDaemonWorkspace(workingDirectory); var lock = File(lockFilePath(workingDirectory)) .openSync(mode: FileMode.write) ..lockSync(); return lock; } on FileSystemException { return null; } } void _createDaemonWorkspace(String workingDirectory) { try { Directory(daemonWorkspace(workingDirectory)).createSync(recursive: true); } catch (e) { throw Exception('Unable to create daemon workspace: $e'); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/change_provider.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'package:watcher/src/watch_event.dart'; abstract class ChangeProvider { /// Returns a list of file changes. /// /// Called immediately before a manual build. If the list is empty a no-op /// build of all tracked targets will be attempted. Future<List<WatchEvent>> collectChanges(); /// A stream of file changes. /// /// A build is triggered upon each stream event. /// /// If multiple files change together then they should be sent in the same /// event. Otherwise, at least two builds will be triggered. Stream<List<WatchEvent>> get changes; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/constants.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:io'; import 'package:path/path.dart' as p; const readyToConnectLog = 'READY TO CONNECT'; const versionSkew = 'DIFFERENT RUNNING VERSION'; const optionsSkew = 'DIFFERENT OPTIONS'; const buildModeFlag = 'build-mode'; enum BuildMode { Manual, Auto, } /// These are used when serializing log messages over stdout. /// /// Serialized logs must be preceded with the [logStartMarker] on its own line, /// and terminated with a [logEndMarker] also on its own line. /// /// This allows multi-line logs to be sanely serialized via stdout, and mixed /// with other generic messages. const logStartMarker = 'BUILD DAEMON LOG START'; const logEndMarker = 'BUILD DAEMON LOG END'; // TODO(grouma) - use pubspec version when this is open sourced. const currentVersion = '8'; var _username = Platform.environment['USER'] ?? ''; String daemonWorkspace(String workingDirectory) { var segments = [Directory.systemTemp.path]; if (_username.isNotEmpty) segments.add(_username); segments.add(workingDirectory .replaceAll('/', '_') .replaceAll(':', '_') .replaceAll('\\', '_')); return p.joinAll(segments); } /// Used to ensure that only one instance of this daemon is running at a time. String lockFilePath(String workingDirectory) => p.join(daemonWorkspace(workingDirectory), '.dart_build_lock'); /// Used to signal to clients on what port the running daemon is listening. String portFilePath(String workingDirectory) => p.join(daemonWorkspace(workingDirectory), '.dart_build_daemon_port'); /// Used to signal to clients the current version of the build daemon. String versionFilePath(String workingDirectory) => p.join(daemonWorkspace(workingDirectory), '.dart_build_daemon_version'); /// Used to signal to clients the current set of options of the build daemon. String optionsFilePath(String workingDirectory) => p.join(daemonWorkspace(workingDirectory), '.dart_build_daemon_options');
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/daemon_builder.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'package:watcher/src/watch_event.dart'; import 'data/build_status.dart'; import 'data/build_target.dart'; import 'data/server_log.dart'; /// A builder for the daemon. /// /// Intended to be used as an interface for specific builder implementations /// which actually do the building. abstract class DaemonBuilder { Stream<BuildResults> get builds; Stream<ServerLog> get logs; Future<void> build(Set<BuildTarget> targets, Iterable<WatchEvent> changes); Future<void> stop(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/data/shutdown_notification.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'shutdown_notification.dart'; // ************************************************************************** // BuiltValueGenerator // ************************************************************************** Serializer<ShutdownNotification> _$shutdownNotificationSerializer = new _$ShutdownNotificationSerializer(); class _$ShutdownNotificationSerializer implements StructuredSerializer<ShutdownNotification> { @override final Iterable<Type> types = const [ ShutdownNotification, _$ShutdownNotification ]; @override final String wireName = 'ShutdownNotification'; @override Iterable<Object> serialize( Serializers serializers, ShutdownNotification object, {FullType specifiedType = FullType.unspecified}) { final result = <Object>[ 'message', serializers.serialize(object.message, specifiedType: const FullType(String)), 'failureType', serializers.serialize(object.failureType, specifiedType: const FullType(int)), ]; return result; } @override ShutdownNotification deserialize( Serializers serializers, Iterable<Object> serialized, {FullType specifiedType = FullType.unspecified}) { final result = new ShutdownNotificationBuilder(); final iterator = serialized.iterator; while (iterator.moveNext()) { final key = iterator.current as String; iterator.moveNext(); final dynamic value = iterator.current; switch (key) { case 'message': result.message = serializers.deserialize(value, specifiedType: const FullType(String)) as String; break; case 'failureType': result.failureType = serializers.deserialize(value, specifiedType: const FullType(int)) as int; break; } } return result.build(); } } class _$ShutdownNotification extends ShutdownNotification { @override final String message; @override final int failureType; factory _$ShutdownNotification( [void Function(ShutdownNotificationBuilder) updates]) => (new ShutdownNotificationBuilder()..update(updates)).build(); _$ShutdownNotification._({this.message, this.failureType}) : super._() { if (message == null) { throw new BuiltValueNullFieldError('ShutdownNotification', 'message'); } if (failureType == null) { throw new BuiltValueNullFieldError('ShutdownNotification', 'failureType'); } } @override ShutdownNotification rebuild( void Function(ShutdownNotificationBuilder) updates) => (toBuilder()..update(updates)).build(); @override ShutdownNotificationBuilder toBuilder() => new ShutdownNotificationBuilder()..replace(this); @override bool operator ==(Object other) { if (identical(other, this)) return true; return other is ShutdownNotification && message == other.message && failureType == other.failureType; } @override int get hashCode { return $jf($jc($jc(0, message.hashCode), failureType.hashCode)); } @override String toString() { return (newBuiltValueToStringHelper('ShutdownNotification') ..add('message', message) ..add('failureType', failureType)) .toString(); } } class ShutdownNotificationBuilder implements Builder<ShutdownNotification, ShutdownNotificationBuilder> { _$ShutdownNotification _$v; String _message; String get message => _$this._message; set message(String message) => _$this._message = message; int _failureType; int get failureType => _$this._failureType; set failureType(int failureType) => _$this._failureType = failureType; ShutdownNotificationBuilder(); ShutdownNotificationBuilder get _$this { if (_$v != null) { _message = _$v.message; _failureType = _$v.failureType; _$v = null; } return this; } @override void replace(ShutdownNotification other) { if (other == null) { throw new ArgumentError.notNull('other'); } _$v = other as _$ShutdownNotification; } @override void update(void Function(ShutdownNotificationBuilder) updates) { if (updates != null) updates(this); } @override _$ShutdownNotification build() { final _$result = _$v ?? new _$ShutdownNotification._( message: message, failureType: failureType); replace(_$result); return _$result; } } // ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/data/build_target.dart
import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; part 'build_target.g.dart'; /// The string representation of a build target, e.g. folder path. abstract class BuildTarget { String get target; } abstract class DefaultBuildTarget implements BuildTarget, Built<DefaultBuildTarget, DefaultBuildTargetBuilder> { static Serializer<DefaultBuildTarget> get serializer => _$defaultBuildTargetSerializer; factory DefaultBuildTarget([void Function(DefaultBuildTargetBuilder) b]) = _$DefaultBuildTarget; DefaultBuildTarget._(); /// A set of file path patterns to match changes against. /// /// If a change matches a pattern this target will not be built. BuiltSet<RegExp> get blackListPatterns; @nullable OutputLocation get outputLocation; /// A set of globs patterns for files to build. /// /// Relative glob paths (from the package) root as well as `package:` uris /// are supported. In the case of a `package:` uri glob syntax is supported /// for the package name as well as the path. /// /// If null then the default is the following patterns: /// - package:*/** /// - $target/** @nullable BuiltSet<String> get buildFilters; } /// The location to write the build outputs. abstract class OutputLocation implements Built<OutputLocation, OutputLocationBuilder> { static Serializer<OutputLocation> get serializer => _$outputLocationSerializer; factory OutputLocation([Function(OutputLocationBuilder b) updates]) = _$OutputLocation; OutputLocation._(); String get output; /// Whether to use symlinks for build outputs. bool get useSymlinks; /// Whether to hoist the build output. /// /// Hoisted outputs will not contain the build target folder within their /// path. /// /// For example hoisting the build target web: /// <web>/<web-contents> /// Should result in: /// <output-folder>/<web-contents> bool get hoist; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/data/build_request.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'build_request.dart'; // ************************************************************************** // BuiltValueGenerator // ************************************************************************** Serializer<BuildRequest> _$buildRequestSerializer = new _$BuildRequestSerializer(); class _$BuildRequestSerializer implements StructuredSerializer<BuildRequest> { @override final Iterable<Type> types = const [BuildRequest, _$BuildRequest]; @override final String wireName = 'BuildRequest'; @override Iterable<Object> serialize(Serializers serializers, BuildRequest object, {FullType specifiedType = FullType.unspecified}) { return <Object>[]; } @override BuildRequest deserialize(Serializers serializers, Iterable<Object> serialized, {FullType specifiedType = FullType.unspecified}) { return new BuildRequestBuilder().build(); } } class _$BuildRequest extends BuildRequest { factory _$BuildRequest([void Function(BuildRequestBuilder) updates]) => (new BuildRequestBuilder()..update(updates)).build(); _$BuildRequest._() : super._(); @override BuildRequest rebuild(void Function(BuildRequestBuilder) updates) => (toBuilder()..update(updates)).build(); @override BuildRequestBuilder toBuilder() => new BuildRequestBuilder()..replace(this); @override bool operator ==(Object other) { if (identical(other, this)) return true; return other is BuildRequest; } @override int get hashCode { return 52408894; } @override String toString() { return newBuiltValueToStringHelper('BuildRequest').toString(); } } class BuildRequestBuilder implements Builder<BuildRequest, BuildRequestBuilder> { _$BuildRequest _$v; BuildRequestBuilder(); @override void replace(BuildRequest other) { if (other == null) { throw new ArgumentError.notNull('other'); } _$v = other as _$BuildRequest; } @override void update(void Function(BuildRequestBuilder) updates) { if (updates != null) updates(this); } @override _$BuildRequest build() { final _$result = _$v ?? new _$BuildRequest._(); replace(_$result); return _$result; } } // ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/data/serializers.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'serializers.dart'; // ************************************************************************** // BuiltValueGenerator // ************************************************************************** Serializers _$serializers = (new Serializers().toBuilder() ..add(BuildRequest.serializer) ..add(BuildResults.serializer) ..add(BuildStatus.serializer) ..add(BuildTargetRequest.serializer) ..add(DefaultBuildResult.serializer) ..add(DefaultBuildTarget.serializer) ..add(Level.serializer) ..add(OutputLocation.serializer) ..add(ServerLog.serializer) ..add(ShutdownNotification.serializer) ..addBuilderFactory( const FullType(BuiltList, const [const FullType(BuildResult)]), () => new ListBuilder<BuildResult>()) ..addBuilderFactory( const FullType(BuiltSet, const [const FullType(RegExp)]), () => new SetBuilder<RegExp>()) ..addBuilderFactory( const FullType(BuiltSet, const [const FullType(String)]), () => new SetBuilder<String>())) .build(); // ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/data/build_status.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; part 'build_status.g.dart'; class BuildStatus extends EnumClass { static const BuildStatus started = _$started; static const BuildStatus succeeded = _$succeeded; static const BuildStatus failed = _$failed; static Serializer<BuildStatus> get serializer => _$buildStatusSerializer; const BuildStatus._(String name) : super(name); static BuildStatus valueOf(String name) => _$valueOf(name); static BuiltSet<BuildStatus> get values => _$values; } /// The build result for a single target. abstract class BuildResult { BuildStatus get status; String get target; @nullable String get buildId; @nullable String get error; @nullable bool get isCached; } abstract class DefaultBuildResult implements BuildResult, Built<DefaultBuildResult, DefaultBuildResultBuilder> { static Serializer<DefaultBuildResult> get serializer => _$defaultBuildResultSerializer; factory DefaultBuildResult([void Function(DefaultBuildResultBuilder) b]) = _$DefaultBuildResult; DefaultBuildResult._(); } /// The group of [BuildResult]s for a single build done by the daemon. /// /// Since the daemon can build multiple targets in parallel, the results are /// grouped together. /// /// Build results will only be provided if the client has registered a target /// that was built. abstract class BuildResults implements Built<BuildResults, BuildResultsBuilder> { static Serializer<BuildResults> get serializer => _$buildResultsSerializer; factory BuildResults([Function(BuildResultsBuilder b) updates]) = _$BuildResults; BuildResults._(); BuiltList<BuildResult> get results; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/data/server_log.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; import 'package:logging/logging.dart' as logging; part 'server_log.g.dart'; /// Logging levels, these have a 1:1 mapping with the levels from /// `package:logging`. class Level extends EnumClass with Comparable<Level> { static Serializer<Level> get serializer => _$levelSerializer; static const Level FINEST = _$finest; static const Level FINER = _$finer; static const Level FINE = _$fine; static const Level CONFIG = _$config; static const Level INFO = _$info; static const Level WARNING = _$warning; static const Level SEVERE = _$severe; static const Level SHOUT = _$shout; const Level._(String name) : super(name); static BuiltSet<Level> get values => _$values; static Level valueOf(String name) => _$valueOf(name); /// Deterministic ordering for comparison. /// /// We don't want to rely on the ordering of `values` since that isn't /// guaranteed. static const _ordered = [ FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, SHOUT, ]; @override int compareTo(Level other) => _ordered.indexOf(this) - _ordered.indexOf(other); bool operator >(Level other) => compareTo(other) > 0; bool operator >=(Level other) => compareTo(other) >= 0; bool operator <(Level other) => compareTo(other) < 0; bool operator <=(Level other) => compareTo(other) <= 0; } /// Converts a [Level] to a [logging.Level]. logging.Level toLoggingLevel(Level level) => logging.Level.LEVELS.firstWhere((l) => l.name == level.name, orElse: () => throw StateError('Unrecognized level `$level`')); /// Roughly matches the `LogRecord` class from `package:logging`. abstract class ServerLog implements Built<ServerLog, ServerLogBuilder> { static Serializer<ServerLog> get serializer => _$serverLogSerializer; factory ServerLog([Function(ServerLogBuilder b) updates]) = _$ServerLog; factory ServerLog.fromLogRecord(logging.LogRecord record) => ServerLog((b) => b ..message = record.message ..level = Level.valueOf(record.level.name) ..loggerName = record.loggerName ..error = record?.error?.toString() ..stackTrace = record.stackTrace?.toString()); logging.LogRecord toLogRecord() { return logging.LogRecord(toLoggingLevel(level), message, loggerName ?? '', error, stackTrace == null ? null : StackTrace.fromString(stackTrace)); } ServerLog._(); Level get level; String get message; @nullable String get loggerName; @nullable String get error; @nullable String get stackTrace; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/data/build_target_request.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; import 'build_target.dart'; part 'build_target_request.g.dart'; /// Registers a build target to be built by the daemon. /// /// Note this does not trigger a build. abstract class BuildTargetRequest implements Built<BuildTargetRequest, BuildTargetRequestBuilder> { static Serializer<BuildTargetRequest> get serializer => _$buildTargetRequestSerializer; factory BuildTargetRequest([Function(BuildTargetRequestBuilder b) updates]) = _$BuildTargetRequest; BuildTargetRequest._(); BuildTarget get target; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/data/serializers.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; import 'build_request.dart'; import 'build_status.dart'; import 'build_target.dart'; import 'build_target_request.dart'; import 'server_log.dart'; import 'shutdown_notification.dart'; part 'serializers.g.dart'; /// Serializers for all the types used in Dart Build Daemon communication. @SerializersFor([ BuildRequest, BuildStatus, BuildResults, BuildTargetRequest, DefaultBuildResult, DefaultBuildTarget, ServerLog, ShutdownNotification, ]) final Serializers serializers = _$serializers;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/data/build_target.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'build_target.dart'; // ************************************************************************** // BuiltValueGenerator // ************************************************************************** Serializer<DefaultBuildTarget> _$defaultBuildTargetSerializer = new _$DefaultBuildTargetSerializer(); Serializer<OutputLocation> _$outputLocationSerializer = new _$OutputLocationSerializer(); class _$DefaultBuildTargetSerializer implements StructuredSerializer<DefaultBuildTarget> { @override final Iterable<Type> types = const [DefaultBuildTarget, _$DefaultBuildTarget]; @override final String wireName = 'DefaultBuildTarget'; @override Iterable<Object> serialize(Serializers serializers, DefaultBuildTarget object, {FullType specifiedType = FullType.unspecified}) { final result = <Object>[ 'blackListPatterns', serializers.serialize(object.blackListPatterns, specifiedType: const FullType(BuiltSet, const [const FullType(RegExp)])), 'target', serializers.serialize(object.target, specifiedType: const FullType(String)), ]; if (object.outputLocation != null) { result ..add('outputLocation') ..add(serializers.serialize(object.outputLocation, specifiedType: const FullType(OutputLocation))); } if (object.buildFilters != null) { result ..add('buildFilters') ..add(serializers.serialize(object.buildFilters, specifiedType: const FullType(BuiltSet, const [const FullType(String)]))); } return result; } @override DefaultBuildTarget deserialize( Serializers serializers, Iterable<Object> serialized, {FullType specifiedType = FullType.unspecified}) { final result = new DefaultBuildTargetBuilder(); final iterator = serialized.iterator; while (iterator.moveNext()) { final key = iterator.current as String; iterator.moveNext(); final dynamic value = iterator.current; switch (key) { case 'blackListPatterns': result.blackListPatterns.replace(serializers.deserialize(value, specifiedType: const FullType(BuiltSet, const [const FullType(RegExp)])) as BuiltSet<dynamic>); break; case 'outputLocation': result.outputLocation.replace(serializers.deserialize(value, specifiedType: const FullType(OutputLocation)) as OutputLocation); break; case 'buildFilters': result.buildFilters.replace(serializers.deserialize(value, specifiedType: const FullType(BuiltSet, const [const FullType(String)])) as BuiltSet<dynamic>); break; case 'target': result.target = serializers.deserialize(value, specifiedType: const FullType(String)) as String; break; } } return result.build(); } } class _$OutputLocationSerializer implements StructuredSerializer<OutputLocation> { @override final Iterable<Type> types = const [OutputLocation, _$OutputLocation]; @override final String wireName = 'OutputLocation'; @override Iterable<Object> serialize(Serializers serializers, OutputLocation object, {FullType specifiedType = FullType.unspecified}) { final result = <Object>[ 'output', serializers.serialize(object.output, specifiedType: const FullType(String)), 'useSymlinks', serializers.serialize(object.useSymlinks, specifiedType: const FullType(bool)), 'hoist', serializers.serialize(object.hoist, specifiedType: const FullType(bool)), ]; return result; } @override OutputLocation deserialize( Serializers serializers, Iterable<Object> serialized, {FullType specifiedType = FullType.unspecified}) { final result = new OutputLocationBuilder(); final iterator = serialized.iterator; while (iterator.moveNext()) { final key = iterator.current as String; iterator.moveNext(); final dynamic value = iterator.current; switch (key) { case 'output': result.output = serializers.deserialize(value, specifiedType: const FullType(String)) as String; break; case 'useSymlinks': result.useSymlinks = serializers.deserialize(value, specifiedType: const FullType(bool)) as bool; break; case 'hoist': result.hoist = serializers.deserialize(value, specifiedType: const FullType(bool)) as bool; break; } } return result.build(); } } class _$DefaultBuildTarget extends DefaultBuildTarget { @override final BuiltSet<RegExp> blackListPatterns; @override final OutputLocation outputLocation; @override final BuiltSet<String> buildFilters; @override final String target; factory _$DefaultBuildTarget( [void Function(DefaultBuildTargetBuilder) updates]) => (new DefaultBuildTargetBuilder()..update(updates)).build(); _$DefaultBuildTarget._( {this.blackListPatterns, this.outputLocation, this.buildFilters, this.target}) : super._() { if (blackListPatterns == null) { throw new BuiltValueNullFieldError( 'DefaultBuildTarget', 'blackListPatterns'); } if (target == null) { throw new BuiltValueNullFieldError('DefaultBuildTarget', 'target'); } } @override DefaultBuildTarget rebuild( void Function(DefaultBuildTargetBuilder) updates) => (toBuilder()..update(updates)).build(); @override DefaultBuildTargetBuilder toBuilder() => new DefaultBuildTargetBuilder()..replace(this); @override bool operator ==(Object other) { if (identical(other, this)) return true; return other is DefaultBuildTarget && blackListPatterns == other.blackListPatterns && outputLocation == other.outputLocation && buildFilters == other.buildFilters && target == other.target; } @override int get hashCode { return $jf($jc( $jc($jc($jc(0, blackListPatterns.hashCode), outputLocation.hashCode), buildFilters.hashCode), target.hashCode)); } @override String toString() { return (newBuiltValueToStringHelper('DefaultBuildTarget') ..add('blackListPatterns', blackListPatterns) ..add('outputLocation', outputLocation) ..add('buildFilters', buildFilters) ..add('target', target)) .toString(); } } class DefaultBuildTargetBuilder implements Builder<DefaultBuildTarget, DefaultBuildTargetBuilder> { _$DefaultBuildTarget _$v; SetBuilder<RegExp> _blackListPatterns; SetBuilder<RegExp> get blackListPatterns => _$this._blackListPatterns ??= new SetBuilder<RegExp>(); set blackListPatterns(SetBuilder<RegExp> blackListPatterns) => _$this._blackListPatterns = blackListPatterns; OutputLocationBuilder _outputLocation; OutputLocationBuilder get outputLocation => _$this._outputLocation ??= new OutputLocationBuilder(); set outputLocation(OutputLocationBuilder outputLocation) => _$this._outputLocation = outputLocation; SetBuilder<String> _buildFilters; SetBuilder<String> get buildFilters => _$this._buildFilters ??= new SetBuilder<String>(); set buildFilters(SetBuilder<String> buildFilters) => _$this._buildFilters = buildFilters; String _target; String get target => _$this._target; set target(String target) => _$this._target = target; DefaultBuildTargetBuilder(); DefaultBuildTargetBuilder get _$this { if (_$v != null) { _blackListPatterns = _$v.blackListPatterns?.toBuilder(); _outputLocation = _$v.outputLocation?.toBuilder(); _buildFilters = _$v.buildFilters?.toBuilder(); _target = _$v.target; _$v = null; } return this; } @override void replace(DefaultBuildTarget other) { if (other == null) { throw new ArgumentError.notNull('other'); } _$v = other as _$DefaultBuildTarget; } @override void update(void Function(DefaultBuildTargetBuilder) updates) { if (updates != null) updates(this); } @override _$DefaultBuildTarget build() { _$DefaultBuildTarget _$result; try { _$result = _$v ?? new _$DefaultBuildTarget._( blackListPatterns: blackListPatterns.build(), outputLocation: _outputLocation?.build(), buildFilters: _buildFilters?.build(), target: target); } catch (_) { String _$failedField; try { _$failedField = 'blackListPatterns'; blackListPatterns.build(); _$failedField = 'outputLocation'; _outputLocation?.build(); _$failedField = 'buildFilters'; _buildFilters?.build(); } catch (e) { throw new BuiltValueNestedFieldError( 'DefaultBuildTarget', _$failedField, e.toString()); } rethrow; } replace(_$result); return _$result; } } class _$OutputLocation extends OutputLocation { @override final String output; @override final bool useSymlinks; @override final bool hoist; factory _$OutputLocation([void Function(OutputLocationBuilder) updates]) => (new OutputLocationBuilder()..update(updates)).build(); _$OutputLocation._({this.output, this.useSymlinks, this.hoist}) : super._() { if (output == null) { throw new BuiltValueNullFieldError('OutputLocation', 'output'); } if (useSymlinks == null) { throw new BuiltValueNullFieldError('OutputLocation', 'useSymlinks'); } if (hoist == null) { throw new BuiltValueNullFieldError('OutputLocation', 'hoist'); } } @override OutputLocation rebuild(void Function(OutputLocationBuilder) updates) => (toBuilder()..update(updates)).build(); @override OutputLocationBuilder toBuilder() => new OutputLocationBuilder()..replace(this); @override bool operator ==(Object other) { if (identical(other, this)) return true; return other is OutputLocation && output == other.output && useSymlinks == other.useSymlinks && hoist == other.hoist; } @override int get hashCode { return $jf($jc( $jc($jc(0, output.hashCode), useSymlinks.hashCode), hoist.hashCode)); } @override String toString() { return (newBuiltValueToStringHelper('OutputLocation') ..add('output', output) ..add('useSymlinks', useSymlinks) ..add('hoist', hoist)) .toString(); } } class OutputLocationBuilder implements Builder<OutputLocation, OutputLocationBuilder> { _$OutputLocation _$v; String _output; String get output => _$this._output; set output(String output) => _$this._output = output; bool _useSymlinks; bool get useSymlinks => _$this._useSymlinks; set useSymlinks(bool useSymlinks) => _$this._useSymlinks = useSymlinks; bool _hoist; bool get hoist => _$this._hoist; set hoist(bool hoist) => _$this._hoist = hoist; OutputLocationBuilder(); OutputLocationBuilder get _$this { if (_$v != null) { _output = _$v.output; _useSymlinks = _$v.useSymlinks; _hoist = _$v.hoist; _$v = null; } return this; } @override void replace(OutputLocation other) { if (other == null) { throw new ArgumentError.notNull('other'); } _$v = other as _$OutputLocation; } @override void update(void Function(OutputLocationBuilder) updates) { if (updates != null) updates(this); } @override _$OutputLocation build() { final _$result = _$v ?? new _$OutputLocation._( output: output, useSymlinks: useSymlinks, hoist: hoist); replace(_$result); return _$result; } } // ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/data/shutdown_notification.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; part 'shutdown_notification.g.dart'; /// An event provided by the daemon to clients immediately before shutdown. abstract class ShutdownNotification implements Built<ShutdownNotification, ShutdownNotificationBuilder> { static Serializer<ShutdownNotification> get serializer => _$shutdownNotificationSerializer; factory ShutdownNotification( [Function(ShutdownNotificationBuilder b) updates]) = _$ShutdownNotification; String get message; int get failureType; ShutdownNotification._(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/data/server_log.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'server_log.dart'; // ************************************************************************** // BuiltValueGenerator // ************************************************************************** const Level _$finest = const Level._('FINEST'); const Level _$finer = const Level._('FINER'); const Level _$fine = const Level._('FINE'); const Level _$config = const Level._('CONFIG'); const Level _$info = const Level._('INFO'); const Level _$warning = const Level._('WARNING'); const Level _$severe = const Level._('SEVERE'); const Level _$shout = const Level._('SHOUT'); Level _$valueOf(String name) { switch (name) { case 'FINEST': return _$finest; case 'FINER': return _$finer; case 'FINE': return _$fine; case 'CONFIG': return _$config; case 'INFO': return _$info; case 'WARNING': return _$warning; case 'SEVERE': return _$severe; case 'SHOUT': return _$shout; default: throw new ArgumentError(name); } } final BuiltSet<Level> _$values = new BuiltSet<Level>(const <Level>[ _$finest, _$finer, _$fine, _$config, _$info, _$warning, _$severe, _$shout, ]); Serializer<Level> _$levelSerializer = new _$LevelSerializer(); Serializer<ServerLog> _$serverLogSerializer = new _$ServerLogSerializer(); class _$LevelSerializer implements PrimitiveSerializer<Level> { @override final Iterable<Type> types = const <Type>[Level]; @override final String wireName = 'Level'; @override Object serialize(Serializers serializers, Level object, {FullType specifiedType = FullType.unspecified}) => object.name; @override Level deserialize(Serializers serializers, Object serialized, {FullType specifiedType = FullType.unspecified}) => Level.valueOf(serialized as String); } class _$ServerLogSerializer implements StructuredSerializer<ServerLog> { @override final Iterable<Type> types = const [ServerLog, _$ServerLog]; @override final String wireName = 'ServerLog'; @override Iterable<Object> serialize(Serializers serializers, ServerLog object, {FullType specifiedType = FullType.unspecified}) { final result = <Object>[ 'level', serializers.serialize(object.level, specifiedType: const FullType(Level)), 'message', serializers.serialize(object.message, specifiedType: const FullType(String)), ]; if (object.loggerName != null) { result ..add('loggerName') ..add(serializers.serialize(object.loggerName, specifiedType: const FullType(String))); } if (object.error != null) { result ..add('error') ..add(serializers.serialize(object.error, specifiedType: const FullType(String))); } if (object.stackTrace != null) { result ..add('stackTrace') ..add(serializers.serialize(object.stackTrace, specifiedType: const FullType(String))); } return result; } @override ServerLog deserialize(Serializers serializers, Iterable<Object> serialized, {FullType specifiedType = FullType.unspecified}) { final result = new ServerLogBuilder(); final iterator = serialized.iterator; while (iterator.moveNext()) { final key = iterator.current as String; iterator.moveNext(); final dynamic value = iterator.current; switch (key) { case 'level': result.level = serializers.deserialize(value, specifiedType: const FullType(Level)) as Level; break; case 'message': result.message = serializers.deserialize(value, specifiedType: const FullType(String)) as String; break; case 'loggerName': result.loggerName = serializers.deserialize(value, specifiedType: const FullType(String)) as String; break; case 'error': result.error = serializers.deserialize(value, specifiedType: const FullType(String)) as String; break; case 'stackTrace': result.stackTrace = serializers.deserialize(value, specifiedType: const FullType(String)) as String; break; } } return result.build(); } } class _$ServerLog extends ServerLog { @override final Level level; @override final String message; @override final String loggerName; @override final String error; @override final String stackTrace; factory _$ServerLog([void Function(ServerLogBuilder) updates]) => (new ServerLogBuilder()..update(updates)).build(); _$ServerLog._( {this.level, this.message, this.loggerName, this.error, this.stackTrace}) : super._() { if (level == null) { throw new BuiltValueNullFieldError('ServerLog', 'level'); } if (message == null) { throw new BuiltValueNullFieldError('ServerLog', 'message'); } } @override ServerLog rebuild(void Function(ServerLogBuilder) updates) => (toBuilder()..update(updates)).build(); @override ServerLogBuilder toBuilder() => new ServerLogBuilder()..replace(this); @override bool operator ==(Object other) { if (identical(other, this)) return true; return other is ServerLog && level == other.level && message == other.message && loggerName == other.loggerName && error == other.error && stackTrace == other.stackTrace; } @override int get hashCode { return $jf($jc( $jc( $jc($jc($jc(0, level.hashCode), message.hashCode), loggerName.hashCode), error.hashCode), stackTrace.hashCode)); } @override String toString() { return (newBuiltValueToStringHelper('ServerLog') ..add('level', level) ..add('message', message) ..add('loggerName', loggerName) ..add('error', error) ..add('stackTrace', stackTrace)) .toString(); } } class ServerLogBuilder implements Builder<ServerLog, ServerLogBuilder> { _$ServerLog _$v; Level _level; Level get level => _$this._level; set level(Level level) => _$this._level = level; String _message; String get message => _$this._message; set message(String message) => _$this._message = message; String _loggerName; String get loggerName => _$this._loggerName; set loggerName(String loggerName) => _$this._loggerName = loggerName; String _error; String get error => _$this._error; set error(String error) => _$this._error = error; String _stackTrace; String get stackTrace => _$this._stackTrace; set stackTrace(String stackTrace) => _$this._stackTrace = stackTrace; ServerLogBuilder(); ServerLogBuilder get _$this { if (_$v != null) { _level = _$v.level; _message = _$v.message; _loggerName = _$v.loggerName; _error = _$v.error; _stackTrace = _$v.stackTrace; _$v = null; } return this; } @override void replace(ServerLog other) { if (other == null) { throw new ArgumentError.notNull('other'); } _$v = other as _$ServerLog; } @override void update(void Function(ServerLogBuilder) updates) { if (updates != null) updates(this); } @override _$ServerLog build() { final _$result = _$v ?? new _$ServerLog._( level: level, message: message, loggerName: loggerName, error: error, stackTrace: stackTrace); replace(_$result); return _$result; } } // ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/data/build_target_request.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'build_target_request.dart'; // ************************************************************************** // BuiltValueGenerator // ************************************************************************** Serializer<BuildTargetRequest> _$buildTargetRequestSerializer = new _$BuildTargetRequestSerializer(); class _$BuildTargetRequestSerializer implements StructuredSerializer<BuildTargetRequest> { @override final Iterable<Type> types = const [BuildTargetRequest, _$BuildTargetRequest]; @override final String wireName = 'BuildTargetRequest'; @override Iterable<Object> serialize(Serializers serializers, BuildTargetRequest object, {FullType specifiedType = FullType.unspecified}) { final result = <Object>[ 'target', serializers.serialize(object.target, specifiedType: const FullType(BuildTarget)), ]; return result; } @override BuildTargetRequest deserialize( Serializers serializers, Iterable<Object> serialized, {FullType specifiedType = FullType.unspecified}) { final result = new BuildTargetRequestBuilder(); final iterator = serialized.iterator; while (iterator.moveNext()) { final key = iterator.current as String; iterator.moveNext(); final dynamic value = iterator.current; switch (key) { case 'target': result.target = serializers.deserialize(value, specifiedType: const FullType(BuildTarget)) as BuildTarget; break; } } return result.build(); } } class _$BuildTargetRequest extends BuildTargetRequest { @override final BuildTarget target; factory _$BuildTargetRequest( [void Function(BuildTargetRequestBuilder) updates]) => (new BuildTargetRequestBuilder()..update(updates)).build(); _$BuildTargetRequest._({this.target}) : super._() { if (target == null) { throw new BuiltValueNullFieldError('BuildTargetRequest', 'target'); } } @override BuildTargetRequest rebuild( void Function(BuildTargetRequestBuilder) updates) => (toBuilder()..update(updates)).build(); @override BuildTargetRequestBuilder toBuilder() => new BuildTargetRequestBuilder()..replace(this); @override bool operator ==(Object other) { if (identical(other, this)) return true; return other is BuildTargetRequest && target == other.target; } @override int get hashCode { return $jf($jc(0, target.hashCode)); } @override String toString() { return (newBuiltValueToStringHelper('BuildTargetRequest') ..add('target', target)) .toString(); } } class BuildTargetRequestBuilder implements Builder<BuildTargetRequest, BuildTargetRequestBuilder> { _$BuildTargetRequest _$v; BuildTarget _target; BuildTarget get target => _$this._target; set target(BuildTarget target) => _$this._target = target; BuildTargetRequestBuilder(); BuildTargetRequestBuilder get _$this { if (_$v != null) { _target = _$v.target; _$v = null; } return this; } @override void replace(BuildTargetRequest other) { if (other == null) { throw new ArgumentError.notNull('other'); } _$v = other as _$BuildTargetRequest; } @override void update(void Function(BuildTargetRequestBuilder) updates) { if (updates != null) updates(this); } @override _$BuildTargetRequest build() { final _$result = _$v ?? new _$BuildTargetRequest._(target: target); replace(_$result); return _$result; } } // ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/data/build_request.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; part 'build_request.g.dart'; /// A request to trigger a build of all registered build targets. abstract class BuildRequest implements Built<BuildRequest, BuildRequestBuilder> { static Serializer<BuildRequest> get serializer => _$buildRequestSerializer; factory BuildRequest([Function(BuildRequestBuilder b) updates]) = _$BuildRequest; BuildRequest._(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/data/build_status.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'build_status.dart'; // ************************************************************************** // BuiltValueGenerator // ************************************************************************** const BuildStatus _$started = const BuildStatus._('started'); const BuildStatus _$succeeded = const BuildStatus._('succeeded'); const BuildStatus _$failed = const BuildStatus._('failed'); BuildStatus _$valueOf(String name) { switch (name) { case 'started': return _$started; case 'succeeded': return _$succeeded; case 'failed': return _$failed; default: throw new ArgumentError(name); } } final BuiltSet<BuildStatus> _$values = new BuiltSet<BuildStatus>(const <BuildStatus>[ _$started, _$succeeded, _$failed, ]); Serializer<BuildStatus> _$buildStatusSerializer = new _$BuildStatusSerializer(); Serializer<DefaultBuildResult> _$defaultBuildResultSerializer = new _$DefaultBuildResultSerializer(); Serializer<BuildResults> _$buildResultsSerializer = new _$BuildResultsSerializer(); class _$BuildStatusSerializer implements PrimitiveSerializer<BuildStatus> { @override final Iterable<Type> types = const <Type>[BuildStatus]; @override final String wireName = 'BuildStatus'; @override Object serialize(Serializers serializers, BuildStatus object, {FullType specifiedType = FullType.unspecified}) => object.name; @override BuildStatus deserialize(Serializers serializers, Object serialized, {FullType specifiedType = FullType.unspecified}) => BuildStatus.valueOf(serialized as String); } class _$DefaultBuildResultSerializer implements StructuredSerializer<DefaultBuildResult> { @override final Iterable<Type> types = const [DefaultBuildResult, _$DefaultBuildResult]; @override final String wireName = 'DefaultBuildResult'; @override Iterable<Object> serialize(Serializers serializers, DefaultBuildResult object, {FullType specifiedType = FullType.unspecified}) { final result = <Object>[ 'status', serializers.serialize(object.status, specifiedType: const FullType(BuildStatus)), 'target', serializers.serialize(object.target, specifiedType: const FullType(String)), ]; if (object.buildId != null) { result ..add('buildId') ..add(serializers.serialize(object.buildId, specifiedType: const FullType(String))); } if (object.error != null) { result ..add('error') ..add(serializers.serialize(object.error, specifiedType: const FullType(String))); } if (object.isCached != null) { result ..add('isCached') ..add(serializers.serialize(object.isCached, specifiedType: const FullType(bool))); } return result; } @override DefaultBuildResult deserialize( Serializers serializers, Iterable<Object> serialized, {FullType specifiedType = FullType.unspecified}) { final result = new DefaultBuildResultBuilder(); final iterator = serialized.iterator; while (iterator.moveNext()) { final key = iterator.current as String; iterator.moveNext(); final dynamic value = iterator.current; switch (key) { case 'status': result.status = serializers.deserialize(value, specifiedType: const FullType(BuildStatus)) as BuildStatus; break; case 'target': result.target = serializers.deserialize(value, specifiedType: const FullType(String)) as String; break; case 'buildId': result.buildId = serializers.deserialize(value, specifiedType: const FullType(String)) as String; break; case 'error': result.error = serializers.deserialize(value, specifiedType: const FullType(String)) as String; break; case 'isCached': result.isCached = serializers.deserialize(value, specifiedType: const FullType(bool)) as bool; break; } } return result.build(); } } class _$BuildResultsSerializer implements StructuredSerializer<BuildResults> { @override final Iterable<Type> types = const [BuildResults, _$BuildResults]; @override final String wireName = 'BuildResults'; @override Iterable<Object> serialize(Serializers serializers, BuildResults object, {FullType specifiedType = FullType.unspecified}) { final result = <Object>[ 'results', serializers.serialize(object.results, specifiedType: const FullType(BuiltList, const [const FullType(BuildResult)])), ]; return result; } @override BuildResults deserialize(Serializers serializers, Iterable<Object> serialized, {FullType specifiedType = FullType.unspecified}) { final result = new BuildResultsBuilder(); final iterator = serialized.iterator; while (iterator.moveNext()) { final key = iterator.current as String; iterator.moveNext(); final dynamic value = iterator.current; switch (key) { case 'results': result.results.replace(serializers.deserialize(value, specifiedType: const FullType( BuiltList, const [const FullType(BuildResult)])) as BuiltList<dynamic>); break; } } return result.build(); } } class _$DefaultBuildResult extends DefaultBuildResult { @override final BuildStatus status; @override final String target; @override final String buildId; @override final String error; @override final bool isCached; factory _$DefaultBuildResult( [void Function(DefaultBuildResultBuilder) updates]) => (new DefaultBuildResultBuilder()..update(updates)).build(); _$DefaultBuildResult._( {this.status, this.target, this.buildId, this.error, this.isCached}) : super._() { if (status == null) { throw new BuiltValueNullFieldError('DefaultBuildResult', 'status'); } if (target == null) { throw new BuiltValueNullFieldError('DefaultBuildResult', 'target'); } } @override DefaultBuildResult rebuild( void Function(DefaultBuildResultBuilder) updates) => (toBuilder()..update(updates)).build(); @override DefaultBuildResultBuilder toBuilder() => new DefaultBuildResultBuilder()..replace(this); @override bool operator ==(Object other) { if (identical(other, this)) return true; return other is DefaultBuildResult && status == other.status && target == other.target && buildId == other.buildId && error == other.error && isCached == other.isCached; } @override int get hashCode { return $jf($jc( $jc( $jc($jc($jc(0, status.hashCode), target.hashCode), buildId.hashCode), error.hashCode), isCached.hashCode)); } @override String toString() { return (newBuiltValueToStringHelper('DefaultBuildResult') ..add('status', status) ..add('target', target) ..add('buildId', buildId) ..add('error', error) ..add('isCached', isCached)) .toString(); } } class DefaultBuildResultBuilder implements Builder<DefaultBuildResult, DefaultBuildResultBuilder> { _$DefaultBuildResult _$v; BuildStatus _status; BuildStatus get status => _$this._status; set status(BuildStatus status) => _$this._status = status; String _target; String get target => _$this._target; set target(String target) => _$this._target = target; String _buildId; String get buildId => _$this._buildId; set buildId(String buildId) => _$this._buildId = buildId; String _error; String get error => _$this._error; set error(String error) => _$this._error = error; bool _isCached; bool get isCached => _$this._isCached; set isCached(bool isCached) => _$this._isCached = isCached; DefaultBuildResultBuilder(); DefaultBuildResultBuilder get _$this { if (_$v != null) { _status = _$v.status; _target = _$v.target; _buildId = _$v.buildId; _error = _$v.error; _isCached = _$v.isCached; _$v = null; } return this; } @override void replace(DefaultBuildResult other) { if (other == null) { throw new ArgumentError.notNull('other'); } _$v = other as _$DefaultBuildResult; } @override void update(void Function(DefaultBuildResultBuilder) updates) { if (updates != null) updates(this); } @override _$DefaultBuildResult build() { final _$result = _$v ?? new _$DefaultBuildResult._( status: status, target: target, buildId: buildId, error: error, isCached: isCached); replace(_$result); return _$result; } } class _$BuildResults extends BuildResults { @override final BuiltList<BuildResult> results; factory _$BuildResults([void Function(BuildResultsBuilder) updates]) => (new BuildResultsBuilder()..update(updates)).build(); _$BuildResults._({this.results}) : super._() { if (results == null) { throw new BuiltValueNullFieldError('BuildResults', 'results'); } } @override BuildResults rebuild(void Function(BuildResultsBuilder) updates) => (toBuilder()..update(updates)).build(); @override BuildResultsBuilder toBuilder() => new BuildResultsBuilder()..replace(this); @override bool operator ==(Object other) { if (identical(other, this)) return true; return other is BuildResults && results == other.results; } @override int get hashCode { return $jf($jc(0, results.hashCode)); } @override String toString() { return (newBuiltValueToStringHelper('BuildResults') ..add('results', results)) .toString(); } } class BuildResultsBuilder implements Builder<BuildResults, BuildResultsBuilder> { _$BuildResults _$v; ListBuilder<BuildResult> _results; ListBuilder<BuildResult> get results => _$this._results ??= new ListBuilder<BuildResult>(); set results(ListBuilder<BuildResult> results) => _$this._results = results; BuildResultsBuilder(); BuildResultsBuilder get _$this { if (_$v != null) { _results = _$v.results?.toBuilder(); _$v = null; } return this; } @override void replace(BuildResults other) { if (other == null) { throw new ArgumentError.notNull('other'); } _$v = other as _$BuildResults; } @override void update(void Function(BuildResultsBuilder) updates) { if (updates != null) updates(this); } @override _$BuildResults build() { _$BuildResults _$result; try { _$result = _$v ?? new _$BuildResults._(results: results.build()); } catch (_) { String _$failedField; try { _$failedField = 'results'; results.build(); } catch (e) { throw new BuiltValueNestedFieldError( 'BuildResults', _$failedField, e.toString()); } rethrow; } replace(_$result); return _$result; } } // ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/src/server.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:built_value/serializer.dart'; import 'package:http_multi_server/http_multi_server.dart'; import 'package:pool/pool.dart'; import 'package:shelf/shelf_io.dart'; import 'package:shelf_web_socket/shelf_web_socket.dart'; import 'package:stream_transform/stream_transform.dart'; import 'package:watcher/watcher.dart'; import 'package:web_socket_channel/web_socket_channel.dart'; import '../change_provider.dart'; import '../daemon_builder.dart'; import '../data/build_request.dart'; import '../data/build_target.dart'; import '../data/build_target_request.dart'; import '../data/serializers.dart'; import '../data/shutdown_notification.dart'; import 'managers/build_target_manager.dart'; /// A server which communicates with build daemon clients over websockets. /// /// Handles notifying clients of logs and results for registered build targets. /// Note the server will only notify clients of pertinent events. class Server { final _isDoneCompleter = Completer(); final BuildTargetManager _buildTargetManager; final _pool = Pool(1); final Serializers _serializers; final ChangeProvider _changeProvider; Timer _timeout; HttpServer _server; final DaemonBuilder _builder; // Channels that are interested in the current build. var _interestedChannels = <WebSocketChannel>{}; final _subs = <StreamSubscription>[]; Server(this._builder, Duration timeout, ChangeProvider changeProvider, {Serializers serializersOverride, bool Function(BuildTarget, Iterable<WatchEvent>) shouldBuild}) : _changeProvider = changeProvider, _serializers = serializersOverride ?? serializers, _buildTargetManager = BuildTargetManager(shouldBuildOverride: shouldBuild) { _forwardData(); _handleChanges(changeProvider.changes); // Stop the server if nobody connects. _timeout = Timer(timeout, () async { if (_buildTargetManager.isEmpty) { await stop(); } }); } Future<void> get onDone => _isDoneCompleter.future; /// Starts listening for build daemon clients. Future<int> listen() async { var handler = webSocketHandler((WebSocketChannel channel) async { channel.stream.listen((message) async { dynamic request; try { request = _serializers.deserialize(jsonDecode(message as String)); } catch (_) { print('Unable to parse message: $message'); return; } if (request is BuildTargetRequest) { _buildTargetManager.addBuildTarget(request.target, channel); } else if (request is BuildRequest) { var changes = await _changeProvider.collectChanges(); var targets = changes.isEmpty ? _buildTargetManager.targets : _buildTargetManager.targetsForChanges(changes); await _build(targets, changes); } }, onDone: () { _removeChannel(channel); }); }); _server = await HttpMultiServer.loopback(0); serveRequests(_server, handler); return _server.port; } Future<void> stop({String message, int failureType}) async { message ??= ''; failureType ??= 0; if (message.isNotEmpty && failureType != 0) { for (var connection in _buildTargetManager.allChannels) { connection.sink .add(jsonEncode(_serializers.serialize(ShutdownNotification((b) => b ..message = message ..failureType = failureType)))); } } _timeout.cancel(); await _server?.close(force: true); await _builder?.stop(); for (var sub in _subs) { await sub.cancel(); } if (!_isDoneCompleter.isCompleted) _isDoneCompleter.complete(); } Future<void> _build( Set<BuildTarget> buildTargets, Iterable<WatchEvent> changes) => _pool.withResource(() { _interestedChannels = buildTargets.expand(_buildTargetManager.channels).toSet(); return _builder.build(buildTargets, changes); }); void _forwardData() { _subs ..add(_builder.logs.listen((log) { var message = jsonEncode(_serializers.serialize(log)); for (var channel in _interestedChannels) { channel.sink.add(message); } })) ..add(_builder.builds.listen((status) { var message = jsonEncode(_serializers.serialize(status)); for (var channel in _interestedChannels) { channel.sink.add(message); } })); } void _handleChanges(Stream<List<WatchEvent>> changes) { _subs.add(changes.asyncMapBuffer((changesLists) async { var changes = changesLists.expand((x) => x).toList(); if (changes.isEmpty) return; if (_buildTargetManager.targets.isEmpty) return; var buildTargets = _buildTargetManager.targetsForChanges(changes); if (buildTargets.isEmpty) return; await _build(buildTargets, changes); }).listen((_) {})); } void _removeChannel(WebSocketChannel channel) async { _buildTargetManager.removeChannel(channel); if (_buildTargetManager.isEmpty) { await stop(); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/src/file_wait.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io'; const _readDelay = Duration(milliseconds: 100); const _maxWait = Duration(seconds: 5); /// Returns true if the file exists. /// /// If the file does not exist it keeps retrying for a period of time. /// Returns false if the file never becomes available. /// /// This reduces the likelihood of race conditions. Future<bool> waitForFile(File file) async { final end = DateTime.now().add(_maxWait); while (!DateTime.now().isAfter(end)) { if (file.existsSync()) return true; await Future.delayed(_readDelay); } return file.existsSync(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/src/fakes/fake_builder.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'package:build_daemon/daemon_builder.dart'; import 'package:build_daemon/data/build_status.dart'; import 'package:build_daemon/data/build_target.dart'; import 'package:build_daemon/data/server_log.dart'; import 'package:watcher/src/watch_event.dart'; class FakeDaemonBuilder implements DaemonBuilder { @override Stream<BuildResults> get builds => Stream.empty(); @override Stream<ServerLog> get logs => Stream.empty(); @override Future<void> build( Set<BuildTarget> targets, Iterable<WatchEvent> changes) async {} @override Future<void> stop() async {} }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_daemon/src/fakes/fake_change_provider.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'package:build_daemon/change_provider.dart'; import 'package:watcher/src/watch_event.dart'; class FakeChangeProvider implements ChangeProvider { @override Stream<List<WatchEvent>> get changes => Stream.empty(); @override Future<List<WatchEvent>> collectChanges() async => []; }
0