Commit graph

3028 commits

Author SHA1 Message Date
Andrew Kaster 012aaecccf AK: Always define ak_assertion_failed, even when NDEBUG is false
Just because we may compile serenity with or without NDEBUG doesn't
mean that consuming projects or Ports will share the setting.

Always define the custom assertion function so that we don't have to
keep the same debug settings between all projects.
2023-02-05 09:46:51 -07:00
MacDue d81a72ed78 AK: Allow propagating errors from StringView::for_each_split_view() 2023-02-05 16:40:51 +01:00
Andreas Kling ed3420dc10 AK: Make WeakPtr<T>::value() return NonnullRefPtr<T>
This API is only used by Jakt to implement weak reference unwrapping.
By making it return a NonnullRefPtr, it can be assigned to anything
that accepts a NonnullRefPtr, unlike the previous T* return type (since
that can also be null).
2023-02-05 15:38:19 +01:00
Lucas CHOLLET 79006c03b4 AK: Check the return type in IsCallableWithArguments
Template argument are checked to ensure that the `Out` type is equal or
convertible to the type returned by the invokee.

Compilation now fails on:
`Function<void()> f = []() -> int { return 0; };`

But this is allowed:
`Function<ErrorOr<int>()> f = []() -> int { return 0; };`
2023-02-04 18:47:02 -07:00
Lucas CHOLLET d9f632fee7 AK: Move the definition of IsCallableWithArguments to Function.h
It will allow us to use definitions from both `StdLibExtraDetails.h` and
`Concepts.h` at the same time.
2023-02-04 18:47:02 -07:00
Lucas CHOLLET e538fa203e AK: Add the ConvertibleTo concept 2023-02-04 18:47:02 -07:00
Tim Schumacher 47531a42a9 AK: Make LEB128 decoding work with read_value 2023-02-04 18:41:27 -07:00
Tim Schumacher 787f4d639a AK: Port LEB128 to the new AK::Stream 2023-02-04 18:41:27 -07:00
Tim Schumacher 31f59855b4 AK: Don't restore the stream offset when failing to read an LEB128
Pretty much no other read function does this, and getting rid of the
typename template parameter for the stream makes the transition to the
new AK::Stream a bit easier.
2023-02-04 18:41:27 -07:00
Tim Schumacher 371c51f934 AK: Make SeekableStream::truncate() take a size_t
Similar to the return values earlier, a signed value doesn't really make
sense here. Relying on the much more standard `size_t` makes it easier
to use Stream in all contexts.
2023-02-04 18:41:27 -07:00
nipos c31b547fae AK: Use constexpr instead of consteval on OpenBSD 2023-02-04 16:11:54 -07:00
Staubfinger da1023fcc5 AK: Add thresholds to quickselect_inline and Statistics::Median
I did a bit of Profiling and made the quickselect and median algorithms
use the best of option for the respective input size.
2023-02-03 19:04:15 +01:00
Staubfinger 6b9344e86c AK: Use AK:quickselect_inline to compute AK::Statistics::median
Quick select is an algorithm that is able to find the median
of a Vector without fully sorting it.
This replaces the old very naive implementation
for `AK::Statistics::median()` with `AK::quickselect_inline`
2023-02-03 19:04:15 +01:00
Staubfinger 607441de56 AK: Implement the quick select algorithm as AK::quickselect_inplace
This adds the quick select algorithm that finds
the kth smallest element for any collection.
Whilst doing so it also partially sorts the collection.
I have also included the option to use different pivoting functions
including median of medians which makes the quick select have
a truely linear time complexity at the costs of enormous overhead,
so this that only really useful for really large datasets.
The same was chosen to reflect the fact that it modifies
the collection in place during the selection process.
2023-02-03 19:04:15 +01:00
Sam Atkins 7d0529b89c AK: Remove JsonObject::get_deprecated() and ::get_ptr() :^) 2023-02-03 07:19:52 -05:00
Timothy Flynn 2af7447dfd AK: Define HashMap::take to find and remove a value from the map 2023-02-02 19:14:00 +00:00
Timothy Flynn f31bd190b0 AK: Ensure string types are actually considered hash-compatible
The AnyString concept is currently broken because it checks whether a
StringView is constructible from a type T. The StringView constructors,
however, only accept constant rvalue references - i.e. `T const&`.

This also adds a test to ensure this continues to work.
2023-02-02 19:14:00 +00:00
Timothy Flynn 2f67f2ba3d AK: Return a constant reference from HashMap's constant get() override
We cannot return a mutable reference from a constant function.
2023-02-02 19:14:00 +00:00
Ben Wiederhake e147d0b572 AK: Fix all quadratic-time append-loops over ByteBuffer 2023-01-31 16:58:25 +01:00
Iman Seyed 0ebcc99e12 AK: Remove unused network ordered 'address' variable 2023-01-31 12:42:49 +01:00
Tim Schumacher 093cf428a3 AK: Move memory streams from LibCore 2023-01-29 19:16:44 -07:00
Tim Schumacher 22f0d04f43 AK: Provide a fallback definition for std::nothrow 2023-01-29 19:16:44 -07:00
Tim Schumacher 2470dd3bb5 AK: Move bit streams from LibCore 2023-01-29 19:16:44 -07:00
Tim Schumacher 94f139c111 AK: Move buffered streams from LibCore 2023-01-29 19:16:44 -07:00
Tim Schumacher 8464da1439 AK: Move Stream and SeekableStream from LibCore
`Stream` will be qualified as `AK::Stream` until we remove the
`Core::Stream` namespace. `IODevice` now reuses the `SeekMode` that is
defined by `SeekableStream`, since defining its own would require us to
qualify it with `AK::SeekMode` everywhere.
2023-01-29 19:16:44 -07:00
Tim Schumacher 5f2ea31816 AK: Move Handle from LibCore and name it MaybeOwned
The new name should make it abundantly clear what it does.
2023-01-29 19:16:44 -07:00
Tim Schumacher 5fa590de71 AK: Remove Buffered 2023-01-29 19:16:44 -07:00
Tim Schumacher ae64b68717 AK: Deprecate the old AK::Stream
This also removes a few cases where the respective header wasn't
actually required to be included.
2023-01-29 19:16:44 -07:00
Andreas Kling 230cb3b0cb AK: Add DeprecatedString::from_utf8()
This will be used in Jakt to help transition off of DeprecatedString.
2023-01-29 23:41:42 +01:00
Andreas Kling 6b497b8710 AK: Add two helpers to DeprecatedStringCodePointIterator 2023-01-29 23:41:42 +01:00
Linus Groh 9c08bb9555 AK: Remove try_ prefix from FixedArray creation functions 2023-01-28 22:41:36 +01:00
Timothy Flynn e96c64cdb4 AK: Add support for the new FlyString to StringView 2023-01-28 15:24:55 +00:00
Timothy Flynn b61f8cd130 AK: Delete the StringView move-assignment operator for various types 2023-01-28 15:24:55 +00:00
Andreas Kling 2dc657c77e AK: Add DeprecatedStringCodePointIterator
This is a safe iterator over the underlying code points. It will be used
in Jakt to assist in the migration away from DeprecatedString.
2023-01-28 09:50:52 +01:00
Timothy Flynn c59268d15b AK: Add String::trim 2023-01-28 00:13:46 +00:00
Timothy Flynn cccaa94767 AK: Add String::join 2023-01-28 00:13:46 +00:00
Timothy Flynn 79aaa2fe0f AK: Allow the kernel to have access to StringBuilder::to_string
This is mostly to prevent String.h from acquiring ifdef-soup. In any
case, it's fine for the kernel to see this symbol as it is fallible.
2023-01-28 00:13:46 +00:00
Linus Groh 6e7459322d AK: Remove StringBuilder::build() in favor of to_deprecated_string()
Having an alias function that only wraps another one is silly, and
keeping the more obvious name should flush out more uses of deprecated
strings.
No behavior change.
2023-01-27 20:38:49 +00:00
Sam Atkins 09a22ddb2a AK: Remove unimplemented methods 2023-01-27 20:33:18 +00:00
Sam Atkins df07c5be3a AK: Remove unused DateTimeLexer class 2023-01-27 20:33:18 +00:00
Timothy Flynn c35b1371a3 AK: Add an overload of String::find_byte_offset for StringView 2023-01-27 18:00:17 +00:00
Timothy Flynn 76fd5f2756 AK: Add convenience substring wrappers to String to exclude a length
These overloads exist on other string classes and are used throughout
the code base.
2023-01-24 16:23:50 -05:00
Timothy Flynn 427b82065c AK: Add a method to create a String with a repeated code point 2023-01-24 16:23:50 -05:00
Timothy Flynn d50724956e AK: Add a method to find the byte offset of a code point 2023-01-24 16:23:50 -05:00
Timothy Flynn 5e44b93af2 AK: Remove [[nodiscard]] attribute from String methods returning ErrorOr 2023-01-24 16:23:50 -05:00
Nico Weber 44de4d163b AK: Make HashMap::try_ensure work with a fallible construction callback
Co-authored-by: Timothy Flynn <trflynn89@pm.me>
2023-01-24 14:45:27 +00:00
Nico Weber 8b5b767465 AK: Print leading zeroes after the dot for FixedPoint numbers
As a nearby comment says, "This is a terrible approximation".
This doesn't make things less terrible, but it does make things
more correct in the given framework of terribleness.

Fixes #17156.
2023-01-24 13:24:21 +01:00
Nico Weber 9c5820326d AK: Make FixedPoint::create_raw public and constexpr 2023-01-23 18:09:23 +00:00
Sam Atkins c7a66882f4 AK: Make NonnullPtrVectors shuffleable
AK::shuffle() doesn't work on these, because their operator[] returns a
reference to the pointed-at value, instead of to the NonnullPtr itself.
2023-01-22 21:31:36 +00:00
Nico Weber aa9037eed4 AK: Add spec comments to Utf16CodePointIterator::operator*() 2023-01-22 21:30:44 +00:00
Timothy Flynn ef275e25b8 AK: Reduce String's allocated data by one byte
This was copied from allocation_size_for_stringimpl, which had to ensure
the string is null-terminated. String makes no such guarantee.
2023-01-22 20:27:52 +00:00
Karol Kosek 2d976ab2a6 AK: Define is_trivially_serializable trait for Little and BigEndian<>
This will allow us get LittleEndian<> and BigEndian<> wrapped types
directly from Stream::read_value<>().
2023-01-22 20:58:42 +01:00
Timothy Flynn 12c8bc3e85 AK: Add a String factory to create a string from a single code point 2023-01-22 01:03:13 +00:00
Timothy Flynn 8aca8e82cb AK: Change String's default constructor to be constant
This allows creating expressions such as:

    constexpr Array<String, 10> {};
2023-01-22 01:03:13 +00:00
Andrew Kaster 7ab37ee22c Everywhere: Remove string.h include from AK/Traits.h and resolve fallout
A lot of places were relying on AK/Traits.h to give it strnlen, memcmp,
memcpy and other related declarations.

In the quest to remove inclusion of LibC headers from Kernel files, deal
with all the fallout of this included-everywhere header including less
things.
2023-01-21 10:43:59 -07:00
Tim Schumacher 63cf9b973d AK: Remove FileStream 2023-01-21 14:43:56 +01:00
martinfalisse aec2dadfdd AK: Add split() for String 2023-01-21 14:35:00 +01:00
Timothy Flynn 4f5353cbb8 AK: Rename double_hash to rehash_for_collision
The name is currently quite confusing as it indicates it hashes doubles.
2023-01-21 10:36:14 +01:00
Timothy Flynn 60b56892ca AK: Add a type alias for DistinctNumeric's underlying type 2023-01-21 10:36:14 +01:00
Tim Schumacher 49b30d3013 AK: Remove InputBitStream and OutputBitStream 2023-01-21 00:45:33 +00:00
Tim Schumacher d7eead4f4c AK: Remove DuplexMemoryStream 2023-01-20 20:48:40 +00:00
Timothy Flynn c8e25a71e0 AK: Disable use of consteval in String::from_utf8_short_string for Apple
This causes an ICE on older versions of clang, and Apple's clang is
currently based on such a version.
2023-01-20 20:33:04 +00:00
Timothy Flynn d48266a420 AK: Support creating known short string literals at compile time
In cases where we know a string literal will fit in the short string
storage, we can do so at compile time without needing to handle error
propagation. If the provided string literal is too long, a compilation
error will be emitted due to the failed VERIFY statement being a non-
constant expression.
2023-01-20 14:24:12 -05:00
Timothy Flynn 5063e218af AK: Move the AK::FixedPoint formatter to FixedPoint.h
This does not need to be defined in Format.h. This causes FixedPoint.h
to be included everywhere. This is particularly going to be an issue
when trying to include <CoreServices/CoreServices.h> on macOS. The macOS
SDK defines its own FixedPoint structure which will conflict with ours.
2023-01-19 11:29:48 +00:00
Peter Elliott b217045f8f AK: Don't write trailing zeros with %g 2023-01-19 12:22:24 +01:00
konrad 9b12571a86 AK: Unify kernel debug messages, avoid printing time if unavailable 2023-01-18 22:58:42 +01:00
konrad 9f736d782c AK: Patch ArbitrarySizedEnum operators for missing constructor
Patch kindly provided by Ali on #aarch64 on Discord.

Co-authored-by: Ali Mohammad Pur <mpfard@serenityos.org>
2023-01-18 22:58:42 +01:00
Timothy Flynn 537fcaf59e AK+LibUnicode: Provide Unicode-aware caseless String matching
The Unicode spec defines much more complicated caseless matching
algorithms in its Collation spec. This implements the "basic" case
folding comparison.
2023-01-18 14:43:40 +00:00
Sam Atkins 79547896b7 AK: Replace uses of JsonObject::get_deprecated()/get_ptr() 2023-01-17 19:52:52 -05:00
Sam Atkins 8d3b268cca AK: Add JsonObject::get...() methods that return Optional
`get()` is intended as a replacement for `get_deprecated()` and `get_ptr
()`. The former returns the same value for "key not found" and "key
found and contains `null`" which is ambiguous. The latter returns a raw
pointer which is spooky. Returning `Optional<JsonValue const&>` covers
all the previous uses for these.

The `get_foo()` methods are helpers to make user code less verbose. Most
of the time, we only want a specific type of value: if we want a number
and get a string, we respond the same as if the value was not there at
all. These make that easier to express.

This also adjusts the `has_i32()` method and friends to examine the
value instead of just looking at the underlying type.
2023-01-17 19:52:52 -05:00
Sam Atkins d1ad63c466 AK: Move JsonObject implementation out of line 2023-01-17 19:52:52 -05:00
Sam Atkins 1dd6b7f5b7 AK+Everywhere: Rename JsonObject::get() to ::get_deprecated()
This is a preparatory step to making `get()` return `ErrorOr`.
2023-01-17 19:52:52 -05:00
Sam Atkins efe4329f9f AK: Add JsonValue::{is,as}_integer() methods
The existing `is_i32()` and friends only check if `i32` is their
internal type, but a value such as `0` could be literally any integer
type internally. `is_integer<T>()` instead determines whether the
contained value is an integer and can fit inside T.
2023-01-17 19:52:52 -05:00
Timothy Flynn d6ddca0c0f AK+LibUnicode: Provide Unicode-aware String titlecase transformation 2023-01-16 18:33:44 -05:00
Timothy Flynn 0a1874c203 AK: Export the OptionalNone helper structure 2023-01-16 10:12:37 +00:00
Tim Schumacher d1711f1cef AK: Define our own concept of "trivially serializable"
While at it, rename the `read_trivial_value` and `write_trivial_value`
functions to `read_value` and `write_value` respectively, since we'll
add compatibility for non-trivial types down the line.
2023-01-15 23:06:31 -05:00
Lucas CHOLLET 3b824ec8c9 AK+Test: Fix a logic error in CircularBuffer::offset_of()
This error was introduced by 9a7accdd and had a significant impact on
`BufferedFile` behavior. Hence, we started seeing crash in test262.

By itself, the issue was a wrong calculation of the internal reading
spans when using the `read` and `until` parameters. Which can lead to
at worse crash in VERIFY and at least weird behaviors as missed needles
or detections out of bounds.

It was also accompanied by an erroneous test.

This patch fixes the bug, the test and also provides more tests.
2023-01-15 23:23:24 +00:00
Timothy Flynn 63c814fa2f AK: Add String::to_number 2023-01-15 01:00:20 +00:00
Timothy Flynn cf0899f440 AK: Add String::contains 2023-01-15 01:00:20 +00:00
Timothy Flynn bd9b65e82f AK: Add String::is_one_of for variadic string comparison 2023-01-15 01:00:20 +00:00
Timothy Flynn 9db9b2f9be AK: Add a somewhat naive implementation of String::reverse
This will reverse the String's code points (i.e. not just its bytes),
but is not aware of grapheme clusters.
2023-01-15 01:00:20 +00:00
Andrew Kaster f5d253dcfa Everywhere: Fully qualify IsLvalueReference in TRY() macros
If USING_AK_GLOBALLY is not defined, the name IsLvalueReference might
not be available in the global namespace. Follow the pattern established
in LibTest to fully qualify AK types in macros to avoid this problem.
2023-01-15 00:56:31 +00:00
Lucas CHOLLET 9a7accddb7 AK: Add an optional starting offset to CircularBuffer::offset_of
This parameter allows to start searching after an offset. For example,
to resume a search.

It is unfortunately a breaking change in API so this patch also modifies
one user and one test.
2023-01-14 16:20:30 -07:00
Lucas CHOLLET 34922c0cc0 AK: Default move operators for CircularBuffer
The previously defined operator was swap-based. With the defaulted
implementation, both integers are now copied, but it doesn't matter as
only the `ByteBuffer` allocates memory (i.e. non-null integers values
won't affect the destruction).
2023-01-14 16:15:31 -07:00
Ben Wiederhake 79b9dd6248 AK+Tests: Make CaseInsensitiveStringViewTraits work with HashMap again 2023-01-14 15:43:27 -07:00
Tim Schumacher 7526f9a8b7 AK: Remove CircularDuplexStream 2023-01-14 12:05:52 -05:00
MacDue 2366265c53 AK: Add StringBuilder::try_join()
This is a failable version of StringBuilder::join().
2023-01-14 12:37:00 +01:00
Tim Schumacher d717a08003 AK: Add CircularBuffer::read_with_seekback 2023-01-13 17:34:45 -07:00
Timothy Flynn afc0e461e1 AK+Everywhere: Disallow returning a reference from a fallible expression
This will silently make a copy. Rather than masking this behavior, let's
explicitly disallow it.
2023-01-13 18:50:47 -05:00
MacDue 9a120d7243 AK: Add support for "debug only" formatters
These are formatters that can only be used with debug print
functions, such as dbgln(). Currently this is limited to
Formatter<ErrorOr<T>>. With this you can still debug log ErrorOr
values (good for debugging), but trying to use them in any
String::formatted() call will fail (which prevents .to_string()
errors with the new failable strings being ignored).

You make a formatter debug only by adding a constexpr method like:
static constexpr bool is_debug_only() { return true; }
2023-01-13 21:09:26 +00:00
MacDue 92cea3216f AK: Don't inherit Formatter<ErrorOr<T>> for Formatter<IPv6Address> 2023-01-13 21:09:26 +00:00
MacDue d5152c49a1 AK: Don't inherit Formatter<ErrorOr<T>> for Formatter<IPv4Address> 2023-01-13 21:09:26 +00:00
MacDue 514224c015 AK: Fix ignored .to_string() errors in IPv6Address 2023-01-12 23:29:57 +00:00
MacDue 35e1e12360 AK: Fix ignored .to_string() errors in IPv4Address 2023-01-12 23:29:57 +00:00
Timothy Flynn 1d4f287582 AK: Implement FlyString for the new String class
This implements a FlyString that will de-duplicate String instances. The
FlyString will store the raw encoded data of the String instance: If the
String is a short string, FlyString holds the String::ShortString bytes;
otherwise FlyString holds a pointer to the Detail::StringData.

FlyString itself does not know about String's storage or how to refcount
its Detail::StringData. It defers to String to implement these details.
2023-01-12 11:23:58 +01:00
Arda Cinar 283187afc5 AK+LibWeb: Move decode forgiving base64 under Web::Infra namespace
Since the forgiving base64 is part of the web infra standard
2023-01-10 17:54:01 +00:00
Arda Cinar 4ab2954210 AK: Expose Base64 tables from Base64.h
This change is necessary to move the forgiving base64 decoder to LibWeb
2023-01-10 17:54:01 +00:00
MacDue 668204041b AK: Add Span::first()
The missing sibling to Span::last()!
2023-01-10 10:25:58 +01:00
Timothy Flynn 6fcc1c7426 AK+LibUnicode: Provide Unicode-aware String case transformations
Since AK can't refer to LibUnicode directly, the strategy here is that
if you need case transformations, you can link LibUnicode and receive
them. If you try to use either of these methods without linking it, then
you'll of course get a linker error (note we don't do any fallbacks to
e.g. ASCII case transformations). If you don't need these methods, you
don't have to link LibUnicode.
2023-01-09 19:23:46 -07:00
Timothy Flynn f3db548a3d AK+Everywhere: Rename FlyString to DeprecatedFlyString
DeprecatedFlyString relies heavily on DeprecatedString's StringImpl, so
let's rename it to A) match the name of DeprecatedString, B) write a new
FlyString class that is tied to String.
2023-01-09 23:00:24 +00:00
Timothy Flynn 2eacc7aec1 AK: Add Utf16View::to_utf8 to convert the view to a UTF-8 AK::String 2023-01-09 23:00:24 +00:00
Timothy Flynn d0403ec14f AK+Everywhere: Rename Utf16View::to_utf8 to to_deprecated_string
A subsequent commit will add to_utf8 back to create an AK::String.
2023-01-09 23:00:24 +00:00
Hendiadyoin1 1bdc4e6b29 AK: Reorder AK/Math after the removal of i686
Without i686 we can remove some implementations for sqrt and round_to.
2023-01-09 11:36:21 +01:00
Timothy Flynn d793262beb AK+Everywhere: Make UTF-16 to UTF-8 converter fallible
This could fail to allocate the underlying storage needed to store the
UTF-8 data. Propagate this error.
2023-01-08 12:13:15 +01:00
Timothy Flynn 1edb96376b AK+Everywhere: Make UTF-8 and UTF-32 to UTF-16 converters fallible
These could fail to allocate the underlying storage needed to store the
UTF-16 data. Propagate these errors.
2023-01-08 12:13:15 +01:00
Timothy Flynn 425c168ded AK+LibJS+LibRegex: Define an alias for UTF-16 string data storage
Instead of writing out "Vector<u16, 1>" everywhere, let's have a name
for it.
2023-01-08 12:13:15 +01:00
Timothy Flynn 39bda0073e AK: Make StringBuilder::try_append_code_point actually fallible
It currently uses the non-fallible `append` method to append each UTF-8
encoded byte of the code point.
2023-01-08 12:13:15 +01:00
Ben Wiederhake 3281050359 Everywhere: Remove "LibC/" includes, add lint-rule against it 2023-01-07 10:01:37 -07:00
Ben Wiederhake d575cfda61 AK: Restrict include of LibC header 2023-01-07 10:01:37 -07:00
Andrew Kaster 64a242261e AK: Reimplement DistinctNumeric comparison operators using operator<=>
Unlike what the class comment says, it's actually valid to return int
from this operator and treat it like a "normal" C-like compare method.
2023-01-07 14:51:04 +01:00
Andrew Kaster a8fcd39b88 AK: Reimplement comparisons on AK::Time using operator<=>
This allows us to make all comparision operators on the class constexpr
without pulling in a bunch of boilerplate. We don't use the `<compare>`
header because it doesn't compile in the main serenity cross-build due
to the include paths to LibC being incompatible with how libc++ expects
them to be for clang builds.
2023-01-07 14:51:04 +01:00
Andrew Kaster 83ad5bfba0 AK: Remove global free function comparison operators for timespec
No code was using these, so let's just delete them. They pollute the
lookup for every single comparison operator in the project.
2023-01-07 14:51:04 +01:00
Andrew Kaster f7025435b2 AK: Add user defined literals for Time for ns, us, ms, and sec
We can use these to simplify Time constants throughout the codebase,
turning Time::from_milliseconds(10) into 10_ms, for example.
2023-01-07 14:51:04 +01:00
Staubfinger 25dd0a4d2d AK: Make Statistics::median return a mean for an even number of values
The previous implementation of Statistics::median() was slightly
incorrect with an even number of elements since in those cases it needs
to be the arithmetic mean of the two elements that share the middle
position.
2023-01-07 12:40:47 +01:00
Thiago Henrique Hupner 401bc13776 AK: Use base URL when the specified URL is empty 2023-01-06 13:59:17 -07:00
Lucas CHOLLET 85bfeba8c6 AK: Support fixed point formatting to print real numbers 2023-01-06 16:05:13 +01:00
Lucas CHOLLET 25e39df7ba AK: Rename StandardFormatter::Mode::Float => FixedPoint 2023-01-06 16:05:13 +01:00
Sam Atkins 6e0ad5536f AK: Export adopt_nonnull_ref_or_enomem to the global namespace 2023-01-06 16:03:50 +01:00
Aliaksandr Kalenik c6d494513e AK: Fix typo in -= operator of DistinctNumeric 2023-01-06 12:01:46 +01:00
Ben Wiederhake 65b420f996 Everywhere: Remove unused includes of AK/Memory.h
These instances were detected by searching for files that include
AK/Memory.h, but don't match the regex:

\\b(fast_u32_copy|fast_u32_fill|secure_zero|timing_safe_compare)\\b

This regex is pessimistic, so there might be more files that don't
actually use any memory function.

In theory, one might use LibCPP to detect things like this
automatically, but let's do this one step after another.
2023-01-02 20:27:20 -05:00
Ben Wiederhake 6b7ce19161 Everywhere: Remove unused includes of LibC/stdlib.h
These instances were detected by searching for files that include
stdlib.h, but don't match the regex:

\\b(_abort|abort|abs|aligned_alloc|arc4random|arc4random_buf|arc4random_
uniform|atexit|atof|atoi|atol|atoll|bsearch|calloc|clearenv|div|div_t|ex
it|_Exit|EXIT_FAILURE|EXIT_SUCCESS|free|getenv|getprogname|grantpt|labs|
ldiv|ldiv_t|llabs|lldiv|lldiv_t|malloc|malloc_good_size|malloc_size|mble
n|mbstowcs|mbtowc|mkdtemp|mkstemp|mkstemps|mktemp|posix_memalign|posix_o
penpt|ptsname|ptsname_r|putenv|qsort|qsort_r|rand|RAND_MAX|random|reallo
c|realpath|secure_getenv|serenity_dump_malloc_stats|serenity_setenv|sete
nv|setprogname|srand|srandom|strtod|strtof|strtol|strtold|strtoll|strtou
l|strtoull|system|unlockpt|unsetenv|wcstombs|wctomb)\\b

(Without the linebreaks.)

This regex is pessimistic, so there might be more files that don't
actually use anything from the stdlib.

In theory, one might use LibCPP to detect things like this
automatically, but let's do this one step after another.
2023-01-02 20:27:20 -05:00
Ben Wiederhake f07847e099 Everywhere: Remove unused includes of AK/Concepts.h
These instances were detected by searching for files that include
AK/Concepts.h, but don't match the regex:

\\b(AnyString|Arithmetic|ArrayLike|DerivedFrom|Enum|FallibleFunction|Flo
atingPoint|Fundamental|HashCompatible|Indexable|Integral|IterableContain
er|IteratorFunction|IteratorPairWith|OneOf|OneOfIgnoringCV|SameAs|Signed
|SpecializationOf|Unsigned|VoidFunction)\\b

(Without the linebreaks.)

This regex is pessimistic, so there might be more files that don't
actually use any concepts.

In theory, one might use LibCPP to detect things like this
automatically, but let's do this one step after another.
2023-01-02 20:27:20 -05:00
Ben Wiederhake c2a900b853 Everywhere: Remove unused includes of AK/StdLibExtras.h
These instances were detected by searching for files that include
AK/StdLibExtras.h, but don't match the regex:

\\b(abs|AK_REPLACED_STD_NAMESPACE|array_size|ceil_div|clamp|exchange|for
ward|is_constant_evaluated|is_power_of_two|max|min|mix|move|_RawPtr|RawP
tr|round_up_to_power_of_two|swap|to_underlying)\\b

(Without the linebreaks.)

This regex is pessimistic, so there might be more files that don't
actually use any "extra stdlib" functions.

In theory, one might use LibCPP to detect things like this
automatically, but let's do this one step after another.
2023-01-02 20:27:20 -05:00
Ben Wiederhake 6fd478b6ce Everywhere: Remove unused includes of AK/Format.h
These instances were detected by searching for files that include
AK/Format.h, but don't match the regex:

\\b(CheckedFormatString|critical_dmesgln|dbgln|dbgln_if|dmesgln|FormatBu
ilder|__FormatIfSupported|FormatIfSupported|FormatParser|FormatString|Fo
rmattable|Formatter|__format_value|HasFormatter|max_format_arguments|out
|outln|set_debug_enabled|StandardFormatter|TypeErasedFormatParams|TypeEr
asedParameter|VariadicFormatParams|v_critical_dmesgln|vdbgln|vdmesgln|vf
ormat|vout|warn|warnln|warnln_if)\\b

(Without the linebreaks.)

This regex is pessimistic, so there might be more files that don't
actually use any formatting functions.

Observe that this revealed that Userland/Libraries/LibC/signal.cpp is
missing an include.

In theory, one might use LibCPP to detect things like this
automatically, but let's do this one step after another.
2023-01-02 20:27:20 -05:00
kleines Filmröllchen a6a439243f Kernel: Turn lock ranks into template parameters
This step would ideally not have been necessary (increases amount of
refactoring and templates necessary, which in turn increases build
times), but it gives us a couple of nice properties:
- SpinlockProtected inside Singleton (a very common combination) can now
  obtain any lock rank just via the template parameter. It was not
  previously possible to do this with SingletonInstanceCreator magic.
- SpinlockProtected's lock rank is now mandatory; this is the majority
  of cases and allows us to see where we're still missing proper ranks.
- The type already informs us what lock rank a lock has, which aids code
  readability and (possibly, if gdb cooperates) lock mismatch debugging.
- The rank of a lock can no longer be dynamic, which is not something we
  wanted in the first place (or made use of). Locks randomly changing
  their rank sounds like a disaster waiting to happen.
- In some places, we might be able to statically check that locks are
  taken in the right order (with the right lock rank checking
  implementation) as rank information is fully statically known.

This refactoring even more exposes the fact that Mutex has no lock rank
capabilites, which is not fixed here.
2023-01-02 18:15:27 -05:00
Ben Wiederhake 3334cf675a AK+Kernel: Eliminate UB (signed overflow) from days_since_epoch 2023-01-02 16:19:35 -05:00
Ben Wiederhake 7a69219a35 AK+Tests: Replace years_to_days_since_epoch by near-instant function
This solves half the problem of #12729. Note that the inverse function
time_to_tm() in LibC/time.cpp still uses a slow for-loop.

See also #13138
2023-01-02 16:19:35 -05:00
Lenny Maiorani e0ab7763da AK: Combine SinglyLinkedList and SinglyLinkedListWithCount
Using policy based design `SinglyLinkedList` and
`SinglyLinkedListWithCount` can be combined into one class which takes
a policy to determine how to keep track of the size of the list. The
default policy is to use list iteration to count the items in the list
each time. The `WithCount` form is a different policy which tracks the
size, but comes with the overhead of storing the count and
incrementing/decrementing on each modification.

This model is extensible to have other forms of counting by
implementing only a new policy instead of implementing a totally new
type.
2023-01-02 20:13:24 +00:00
Arda Cinar 0dbb1be81c AK: Add an option to format numbers with 1000 based units
Instead of only allowing 1024-based units.
2023-01-02 20:11:18 +00:00
Arda Cinar ccb6b4f943 AK: Make sure no overflow occurs in number_string_with_one_decimal
A possible integer overflow might have occured inside the function in
case (number % unit) * 10 did not fit into a u64. So it is verified that
this does not happen at the beginning of the function.
2023-01-02 20:11:18 +00:00
Arda Cinar c8fadff9b1 AK: Add a human_readable_quantity helper to NumberFormat.h
This can be used for displaying large quantities that are not measured
in bytes in a more human-readable format.
2023-01-02 20:11:18 +00:00
Arda Cinar 3e924e2a37 AK: Move the functions in NumberFormat.h out of line 2023-01-02 20:11:18 +00:00
Ben Wiederhake c1676cdddb Everywhere: Remove unused includes of AK/IterationDecision.h
These instances were detected by searching for files that include
IterationDecision.h, but don't match the regex:
\\bIterationDecision(?!\.h>)\\b
This is the only symbol defined by IterationDecision.h.

In theory, one might use LibCPP to detect things like this
automatically, but let's do this one step after another.
2023-01-02 20:08:35 +00:00
Ben Wiederhake a8391d5a60 Everywhere: Remove unused includes of AK/Array.h
These instances were detected by searching for files that include
Array.h, but don't match the regex:
\\b(Array(?!\.h>)|iota_array|integer_sequence_generate_array)\\b
These are the three symbols defined by Array.h.

In theory, one might use LibCPP to detect things like this
automatically, but let's do this one step after another.
2023-01-02 20:08:35 +00:00
Ben Wiederhake b83cb09db1 Everywhere: Fix badly-formatted includes
In 7c5e30daaa, the focus was "only" on
Userland/Libraries/, whereas this commit cleans up the remaining
headers in the repo, and any new badly-formatted include.
2023-01-02 11:06:15 -05:00
Nico Weber 25171e310b AK: Prefer VERIFY_NOT_REACHED in ByteBuffer 2022-12-31 23:20:37 +01:00
Lucas CHOLLET f12e81b74a AK: Add CircularBuffer
The class is very similar to `CircularDuplexStream` in its behavior.
Main differences are that `CircularBuffer`:
 - does not inherit from `AK::Stream`
 - uses `ErrorOr` for its API
 - is heap allocated (and OOM-Safe)

 This patch also add some tests.
2022-12-31 04:44:17 -07:00
Timon Kruiper b18a7297c5 Kernel: Move ScopedCritical.cpp to Kernel base directory
This file does not contain any architecture specific implementations,
so we can move it to the Kernel base directory. Also update the relevant
include paths.
2022-12-29 19:32:20 -07:00
Sam Atkins feb0eb9309 AK: Fix constructing ErrorOr from ErrorOr of a related type
Mark other ErrorOr types as friends, and fix a typo in the &&
constructor, so that we can create an ErrorOr<Core::Object> from an
ErrorOr<GUI::Widget>. Also, add some requires() clauses to these
constructors so the error messages are clearer.
2022-12-28 22:34:00 -05:00
Arda Cinar bbaf86fb46 AK: Add a forgiving_base64_decode helper
According to the specification at
https://infra.spec.whatwg.org/#forgiving-base64
2022-12-28 21:15:02 +01:00
Nico Weber 57126a0d3c AK: Make BigEndian<> and LittleEndian<> work with enum classes 2022-12-28 20:13:12 +00:00
Andreas Kling c0e3bdd51b AK: Remove ARCH(I386) macro 2022-12-28 11:53:41 +01:00
Liav A feeb25bcee AK: Remove i686 support 2022-12-28 11:53:41 +01:00
Florian Cramer af2ffcaba8 AK: Make StringUtils::matches() handle escaping correctly
Previously any backslash and the character following it were ignored.
This commit adds a fall through to match the character following the
backslash without checking whether it is "special".
2022-12-27 07:28:25 +03:30
Nico Weber 8932b28b8a AK: Mark Error::from_ functions as [[nodiscard]]
Prevents mistakes like the one fixed in #16672.
2022-12-26 13:56:13 -05:00
Timothy Flynn d2a304ae87 AK: Specialize TypeList for Variant types
This allows callers to use the following semantics:

    using MyVariant = Variant<Empty, int>;

    template<typename T>
    size_t size() { return TypeList<T>::size; }

    auto s = size<MyVariant>();

This will be needed for an upcoming IPC change, which will result in us
knowing the Variant type, but not the underlying variadic types that the
Variant holds.
2022-12-26 09:36:16 +01:00
Alec Murphy da4067a75f AK: Remove tilde from URL::PercentEncodeSet::EncodeURI 2022-12-26 04:51:55 +03:30
Timothy Flynn 4b4b15adb1 AK: Rearrange Error's members to reduce its size by 8 bytes
This shrinks sizeof(Error) from 32 bytes to 24 bytes, which in turn will
shrink sizeof(ErrorOr<T>) by the same amount (in cases where sizeof(T)
is less than sizeof(Error)).
2022-12-22 14:13:56 -05:00
Sam Atkins 29733e65f8 AK+Everywhere: Replace all Bitmap::must_create() uses with ::create()
Well, *someone* has to add some more FIXMEs to keep FIXME Roulette
going. :^)
2022-12-22 15:48:53 +01:00
Sam Atkins bed5961fc2 AK: Rename Bitmap::try_create() to ::create()
This is step 1 to removing `must_create()`.
2022-12-22 15:48:53 +01:00
Karol Kosek 25fa485dfb AK: Calculate elapsed days in human_readable_time() 2022-12-21 08:41:34 +00:00
Agustin Gianni 9a2ee5a9dd AK: Add DeprecatedString::find_last(StringView)
This adds the the method DeprecatedString::find_last() as wrapper for
StringUtils::find_last for the StringView type.
2022-12-20 11:24:05 +01:00
Jelle Raaijmakers 25f2e4981c AK: Stop using DeprecatedString in Base64 encoding 2022-12-20 10:34:19 +01:00
Jelle Raaijmakers 99c1b634fc AK: Stop using DeprecatedString in UUID 2022-12-20 10:34:19 +01:00
Andreas Kling f11e6beca8 AK: Use __has_builtin() in Checked.h
Instead of avoiding overflow-checking builtins with AK_COMPILER_CLANG,
we can use the preprocessor's __has_builtin() mechanism to check if
they are available.
2022-12-19 09:29:12 -05:00
Lenny Maiorani f2336d0144 AK+Everywhere: Move custom deleter capability to OwnPtr
`OwnPtrWithCustomDeleter` was a decorator which provided the ability
to add a custom deleter to `OwnPtr` by wrapping and taking the deleter
as a run-time argument to the constructor. This solution means that no
additional space is needed for the `OwnPtr` because it doesn't need to
store a pointer to the deleter, but comes at the cost of having an
extra type that stores a pointer for every instance.

This logic is moved directly into `OwnPtr` by adding a template
argument that is defaulted to the default deleter for the type. This
means that the type itself stores the pointer to the deleter instead
of every instance and adds some type safety by encoding the deleter in
the type itself instead of taking a run-time argument.
2022-12-17 16:00:08 -05:00
Eli Youngs 950b36f95d AK: Add a try_ensure() method to HashMap 2022-12-16 10:41:56 -07:00
Eli Youngs a2024cfb69 AK: Support popping an arbitrary element from a HashTable 2022-12-16 10:41:56 -07:00
Timothy Flynn d28c9ba054 AK: Synchronize explicit instantiations of to_int and to_uint
1. Ensure long and long long are instantiated for to_int.
2. Ensure long and long long are not instantiated for to_uint.
2022-12-16 10:06:26 +01:00
Lucas CHOLLET 34c13eff11 AK: Add OwnPtrWithCustomDeleter
This class is a smart pointer that let you provide a custom deleter to
free the pointer.

It is quite primitive compared to other smart pointers but can still be
useful when interacting with C types that provides a custom `free()`
function.
2022-12-15 13:38:13 +00:00
kleines Filmröllchen 026cc3d4b9 AK: Add Span to Array conversion function 2022-12-15 00:21:00 -07:00
Poseydon42 bdd7531bf5 AK: Create relative path even if prefix is not an ancestor of the path 2022-12-14 15:11:03 +00:00
Ali Mohammad Pur b367da592c AK: Bring back the AK_DONT_REPLACE_STD #define
This was removed in a910961f37d1da9dafb6385e348266746354cf98 in favour
of the more general USING_AK_GLOBALLY #define, but Ladybird (and
probably other projects) depend on the smaller hammer to include STL
headers and keep the USING_AK_GLOBALLY behaviour, so put it back and
preserve its behaviour.
2022-12-14 12:56:01 +01:00
Ali Mohammad Pur f96a3c002a Everywhere: Stop shoving things into ::std and mentioning them as such
Note that this still keeps the old behaviour of putting things in std by
default on serenity so the tools can be happy, but if USING_AK_GLOBALLY
is unset, AK behaves like a good citizen and doesn't try to put things
in the ::std namespace.

std::nothrow_t and its friends get to stay because I'm being told that
compilers assume things about them and I can't yeet them into a
different namespace...for now.
2022-12-14 11:44:32 +01:00
Ali Mohammad Pur 72514d6915 AK: Make Types.h not export its functions if !USING_AK_GLOBALLY 2022-12-14 11:44:32 +01:00
kleines Filmröllchen 5b4818df22 AK: Make Variant's index type public
This will allow the IPC system to use the exact required index type,
saving transmission space, once it can send variants.
2022-12-13 10:24:59 -05:00
Ali Mohammad Pur ad120606fd AK: Fix build with !USING_AK_GLOBALLY
A couple headers expected names to be in the global namespace, qualify
those names to make sure they're resolved even when the names are not
exported.
One header placed its functions in the global namespace, move those to
the AK namespace to make the concepts resolve.
2022-12-13 08:09:56 +03:30
Ali Mohammad Pur d987ddc0ee AK: Actually don't include <unistd.h> for windows in Platform.h
I got the conditions wrong last time, oops :^)
2022-12-12 17:01:16 +00:00
Arda Cinar 1cdd3bb74f AK: Add a shuffle utility function
This implements a shuffle function in AK/Random.h which works on any
container with size() and curly brace operators. It uses fisher-yates
shuffle.
2022-12-12 16:23:03 +00:00
Lucas CHOLLET 6c83bd8fd4 AK: Introduce the DerivedFrom concept 2022-12-12 16:21:39 +00:00
Ali Mohammad Pur 4aa70a07ca AK: Don't use <random> on windows for ::rand()
This is the same as the libc function, just use the libc function.
2022-12-12 15:05:48 +00:00
Ali Mohammad Pur 06816deb78 AK: Don't try to include <unistd.h> on windows for PAGE_SIZE 2022-12-12 15:05:48 +00:00
kleines Filmröllchen b81a457de5 AK: Change quicksort comments to standard // style 2022-12-12 15:03:57 +00:00
Marc Luqué 22f472249d AK: Introduce cutoff to insertion sort for Quicksort
Implement insertion sort in AK. The cutoff value 7 is a magic number
here, values [5, 15] should work well. Main idea of the cutoff is to
reduce recursion performed by quicksort to speed up sorting
of small partitions.
2022-12-12 15:03:57 +00:00
kleines Filmröllchen bbb256e8b5 AK: Introduce Indexable concept
This was dearly missing and can be used in many existing templates.
2022-12-12 15:03:57 +00:00
Ali Mohammad Pur fc805e8f03 AK: Specialise AK::is() for NNRP<T>
This is used by the Jakt runtime.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 18bc88b806 AK: Add an identity implementation of StringView::from_string_literal()
This is required for the Jakt runtime.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur e591c604de AK: Add Optional-like value()/has_value() getters to WeakPtr 2022-12-11 20:44:54 +03:30
Ali Mohammad Pur c373c2deb0 AK: Allow constructing WeakPtr<T> using OptionalNone
The Jakt runtime requires this.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 96b36203a2 AK: Add Optional::lazy_emplace(Callable)
This makes it possible to emplace using a given function instead of
passing constructor arguments.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 0ed9fe3864 AK: Allow non-ascii characters to be printed
This keeps the FIXME, as well as the assertion.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 08fc42002c AK: Format the contents of NNRP<T> if T is formattable 2022-12-11 20:44:54 +03:30
Ali Mohammad Pur ff038f306a AK: Ignore "alternative" formatting of StringView instead of crashing
Jakt implements this in a different way, but it's a noop for
StringViews anyway.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 1cc8cdcd23 AK: Add a Error::__jakt_from_string_literal(StringView) factory function
Note that Jakt only allows StringView creation from string literals, so
none of the invariants in the class are broken by this (if used only
from within Jakt).
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 537924a8d0 AK: Let ErrorOr<T, E> expose its result/error types
`ErrorOr<T, E>::ResultType` can now refer to `T`.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur c3b4b0e88b AK: Add support for modulo to Checked<T>
This is used by the Jakt runtime.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur cc0b970d81 AK: Allow Optional<T> to be constructed by OptionalNone()
This is needed by the Jakt runtime too.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 12e4cd3b77 AK: Allow the user to access the variant index
The average user has no need for this, but the Jakt compiler uses this
to avoid going through the expensive ::visit() and ::get<>() APIs.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 543890c5c9 AK: Add a fallible StringBuilder::create() factory function
This is nice, and is also used by the Jakt runtime.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 21c2d8bd98 AK: Add a Optional::value_or_lazy_evaluated(constructor_function) API
This allows the user to avoid constructing the default value if the
optional already contains a value.
This is used by the Jakt runtime.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur cc948d06a6 AK: Add a functional-style Optional::map(mapper_function) API
This allows the user to transform the contents of the optional (if any
exists), without manually unwrapping and then rewrapping it.
This is needed by the Jakt runtime.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 5809b4aafa AK: Let HashMap also take a ValueTraits
We were previously using Traits<V>, take that frrom the template
parameters instead.
This is needed by the Jakt runtime.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 58252a7684 AK: Elaborate the Error constructors a bit
The old constraints were making clang mad, so express them in a less
complex way.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 099a6bc45f AK: Give DeprecatedString::replace() a default mode
This is used in Jakt, and providing that value from Jakt's side is more
trouble than doing this.
Considering this class is bound to go away, a little
backwards-compatible API change is just fine.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 7a17fd6d71 AK: Add a DeprecatedString::byte_at() getter
`operator[]` returns a char, this is used in Jakt.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur c547b55a00 AK: Add a Checked::unchecked_value() function
This is used in Jakt.
2022-12-11 20:44:54 +03:30
kleines Filmröllchen 16ca41ec10 AK: Add LexicalPath::is_child_of
This API checks whether this path is a child of (or the same as) another
path.
2022-12-11 16:05:23 +00:00
kleines Filmröllchen f502e24bd7 AK: Change the moved-from String state to the empty short string
The previous moved-from state was the null string. This violates both
our invariant that String is never null, and also the C++ contract that
the moved-from state must be valid but unspecified. The empty short
string state is of course valid, so it satisfies both invariants. It
also allows us to remove any extra checks for the null state.

The reason this change is made is primarily because swap() requires
moved-from objects to be reassignable (C++ allows this). Because the
move assignment of String would not check the null state, it crashed
trying to increment the data reference count (nullptr signals a
non-short string). This meant that e.g. quick_sort'ing String would
crash immediately.
2022-12-11 16:05:23 +00:00
kleines Filmröllchen ca80353efe AK: Add comparison operator
s p a c e s h i p  o p e r a t o r

Comparing UTF-8 can be done by simple byte lexicographic comparison per
definition, so we just piggy-back on StringView's high-performance
comparator.
2022-12-11 16:05:23 +00:00
Thomas Queiroz 54c12b76ed AK: Remove HashMap::ensure_capacity
This is not perfect, since the constuctor can still fail.
2022-12-10 14:29:46 +01:00