Commit Graph

2721 Commits

Author SHA1 Message Date
Linus Groh
4db85493e8 AK+Meta: Add WEB_FETCH_DEBUG macro 2022-10-30 20:10:29 +00:00
demostanis
7c33f8f7df AK: Add SplitBehavior::KeepTrailingSeparator with tests 2022-10-24 23:29:18 +01:00
demostanis
3e8b5ac920 AK+Everywhere: Turn bool keep_empty to an enum in split* functions 2022-10-24 23:29:18 +01:00
davidot
c9aa664eb0 AK: Make the JsonParser use the new double parser for numbers
Because we still support u64 and i64 (on top of i32 and u32) we do still
have to parse the number ourself first. Then if we determine that the
number is a floating point or is outside of the range of i64 and u64 we
fallback and parse it as a double.

Before JsonParser had ifdefs guarding the double computation, but it
just build when we error on ifdef KERNEL so JsonParser is no longer
usable in the Kernel. This can be remedied fairly easily but since
it is not needed we #error on that for now.
2022-10-23 15:48:45 +02:00
davidot
6fd8e96d53 AK: Add to_{double, float} convenience functions to all string types
These are guarded with #ifndef KERNEL, since doubles (and floats) are
not allowed in KERNEL mode.
In StringUtils there is convert_to_floating_point which does have a
template parameter incase you have a templated type.
2022-10-23 15:48:45 +02:00
davidot
2334cd85a2 AK: Add an exact and fast hex float parsing algorithm
Similar to decimal floating point parsing the current strtod hex float
parsing gives a lot of incorrect results. We can use a similar technique
as with decimal parsing however hex floats are much simpler as we don't
need to scale with a power of 5.

For hex floats we just provide the parse_first_hexfloat API as there is
currently no need for a parse_hexfloat_completely API.

Again the accepted input for parse_first_hexfloat is very lenient and
any validation should be done before calling this method.
2022-10-23 15:48:45 +02:00
davidot
53b7f5e6a1 AK: Add an exact and fast floating point parsing algorithm
This is based on the paper by Daniel Lemire called
"Number parsing at a Gigabyte per second", currently available at
https://arxiv.org/abs/2101.11408
An implementation can be found at
https://github.com/fastfloat/fast_float

To support both strtod like methods and String::to_double we have two
different APIs. The parse_first_floating_point gives back both the
result, next character to read and the error/out of range status.
Out of range here means we rounded to infinity 0.

The other API, parse_floating_point_completely, will return a floating
point only if the given character range contains just the floating point
and nothing else. This can be much faster as we can skip actually
computing the value if we notice we did not parse the whole range.

Both of these APIs support a very lenient format to be usable in as many
places as possible. Also it does not check for "named" values like
"nan", "inf", "NAN" etc. Because this can be different for every usage.

For integers and small values this new method is not faster and often
even a tiny bit slower than the current strtod implementation. However
the strtod implementation is wrong for a lot of values and has a much
less predictable running time.

For correctness this method was tested against known string -> double
datasets from https://github.com/nigeltao/parse-number-fxx-test-data
This method gives 100% accuracy.
The old strtod gave an incorrect value in over 50% of the numbers
tested.
2022-10-23 15:48:45 +02:00
davidot
bf6d4a5cbf AK: Make truncating UFixedBigInts constexpr
Also add some tests and shift tests while we're at it.
2022-10-23 15:48:45 +02:00
Timothy Flynn
b9dc0b7d1b AK: Do not append string bytes as code points when title-casing a string
By appending individual bytes as code points, we were "breaking apart"
multi-byte UTF-8 code points. This now behaves the same way as the
invert_case() helper in StringUtils.
2022-10-20 18:55:43 +02:00
Timon Kruiper
c7aa05cdcc Kernel/aarch64: Initialize TimeManagement in init.cpp
Also remove the check for aarch64 in AK/Format.cpp, so now the format
functions will prepend the time since boot!
2022-10-17 20:11:31 +02:00
Paul Herman
d989c50c90 AK: Document the non-standard extensions in TRY
I'm not sure there's a material improvement from this patch. However,
I've been reading the error handling code from multiple projects and
was excited to see Serenity being able to handle assignment
(`auto x = TRY(make_x())`) the same way as actions (`TRY(do_x())`).
I think it's worth documenting that this is only possible due to
non-standard extensions.
2022-10-16 22:05:42 +02:00
Gunnar Beutner
918fdf9e2c Kernel: Add VALIDATE_IS_AARCH64 guard macro 2022-10-16 17:35:37 +02:00
Andrew Kaster
1ca48a2aec AK+Userland: Use a CMake variable for AK_SOURCES instead of GLOB
This lets us remove a glob pattern from LibC, the DynamicLoader, and,
later, Lagom. The Kernel already has its own separate list of AK files
that it wants, which is only a subset of all AK files.
2022-10-16 16:36:39 +02:00
Undefine
9718667bcf AK: Add StringView::find_last_not 2022-10-14 18:36:40 -06:00
Timothy Flynn
d007337d97 AK: Explictly disallow lvalue reference types within Variant
This prevents an ICE with GCC trying to declare e.g. Variant<String&>.

Using a concept is a bit overkill here, but clang otherwise trips over
the friendship declaration to other Variant types:

    template<typename... NewTs>
    friend struct Variant;

Without using a concept, clang believes this is re-declaring the Variant
type with differing requirements ("error: requires clause differs in
template redeclaration").
2022-10-15 01:26:14 +02:00
demostanis
aa788581f2 AK: Make StringUtils::matches() handle escaping 2022-10-14 13:37:29 +02:00
Gunnar Beutner
7a8206197e AK: Stub out the NAKED macro on AARCH64
This is almost certainly incorrect but we'll see about that once
the kernel actually gets to userspace init.
2022-10-14 13:01:13 +02:00
Gunnar Beutner
a650c74b27 AK+Toolchain: Make char and wchar_t behave on AARCH64
By default char and wchar_t are unsigned on AARCH64. This fixes a
bunch of related compiler errors.
2022-10-14 13:01:13 +02:00
Gunnar Beutner
31bd5b1a02 AK+Userland: Stub out code that isn't currently implemented on AARCH64
Even though this almost certainly wouldn't run properly even if we had
a working kernel for AARCH64 this at least lets us build all the
userland binaries.
2022-10-14 13:01:13 +02:00
Hendiadyoin1
a143d666db AK: Fix aarch64 versions of math functions
These were incorrectly assumed to compile, but did indeed still have
a few issues.
2022-10-14 11:06:28 +02:00
Hendiadyoin1
eb5651870e AK: Add support for some trivial math functions on aarch64
These all require just a single instruction each, we only have to
differentiate between register prefixes accordingly.
2022-10-14 00:28:34 +02:00
Al Hoang
d7d50d6d9e AK: Fix FreeBSD compilation for clock
FreeBSD introduced CLOCK_MONOTONIC_COARSE and CLOCK_REALTIME_COARSE.
This update fixes ladybird builds from FreeBSD 13.1

see clock_gettime(2) https://www.freebsd.org/cgi/man.cgi?query=clock_gettime&apropos=0&sektion=0&manpath=FreeBSD+13.1-RELEASE&arch=default&format=ascii
2022-10-12 23:12:13 -06:00
Sam Atkins
80603f141a WebDriver: Add new WebDriver service
WebDriver aims to implement the WebDriver specification found at
https://w3c.github.io/webdriver/webdriver-spec.html . It's an HTTP
server that can create Browser sessions and control them.

Co-authored-by: Florent Castelli <florent.castelli@gmail.com>
2022-10-12 23:07:42 +02:00
Sam Atkins
a0d44026fc AK+Tests: Correct off-by-one error when right-trimming text
If the entire string you want to right-trim consists of characters you
want to remove, we previously would incorrectly leave the first
character there.

For example: `trim("aaaaa", "a")` would return "a" instead of "".

We can't use `i >= 0` in the loop since that would fail to detect
underflow, so instead we keep `i` in the range `size .. 1` and then
subtract 1 from it when reading the character.

Added some trim() tests while I was at it. (And to confirm that this was
the issue.)
2022-10-11 17:49:32 +02:00
Andrew Kaster
1d533acbc0 AK+Userland: Replace Linux, macOS, and *BSD macros with platform defines
We have such nice platform macros, let's clean up any remnants of manual
__my_platform__ macros in LibCore, LibCompress and AK.
2022-10-10 12:23:12 +02:00
Andrew Kaster
828441852f Everywhere: Replace uses of __serenity__ with AK_OS_SERENITY
Now that we have OS macros for essentially every supported OS, let's try
to use them everywhere.
2022-10-10 12:23:12 +02:00
Ben Wiederhake
dc71e1e264 AK: Fix 'constexpr' attribute on non-constexpr function
is_url_code_point invokes StringView::contains, which never was and
cannot become constexpr.
2022-10-09 10:37:20 -06:00
Ben Wiederhake
ff8f3814cc AK+Tests: Avoid creating invalid code points from malformed UTF-8
Instead of doing anything reasonable, Utf8CodePointIterator returned
invalid code points, for example U+123456. However, many callers of this
iterator assume that a code point is always at most 0x10FFFF.

In fact, this is one of two reasons for the following OSS Fuzz issue:
https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=49184
This is probably a very old bug.

In the particular case of URLParser, AK::is_url_code_point got confused:
    return /* ... */ || code_point >= 0xA0;
If code_point is a "code point" beyond 0x10FFFF, this violates the
condition given in the preceding comment, but satisfies the given
condition, which eventually causes URLParser to crash.

This commit fixes *only* the erroneous UTF-8 decoding, and does not
fully resolve OSS-Fuzz#49184.
2022-10-09 10:37:20 -06:00
Ben Wiederhake
3aeb57ed09 AK+Everywhere: Fix data corruption due to code-point-to-char conversion
In particular, StringView::contains(char) is often used with a u32
code point. When this is done, the compiler will for some reason allow
data corruption to occur silently.

In fact, this is one of two reasons for the following OSS Fuzz issue:
https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=49184
This is probably a very old bug.

In the particular case of URLParser, AK::is_url_code_point got confused:
    return /* ... */ || "!$&'()*+,-./:;=?@_~"sv.contains(code_point);
If code_point is a large code point that happens to have the correct
lower bytes, AK::is_url_code_point is then convinced that the given
code point is okay, even if it is actually problematic.

This commit fixes *only* the silent data corruption due to the erroneous
conversion, and does not fully resolve OSS-Fuzz#49184.
2022-10-09 10:37:20 -06:00
Timothy Flynn
e897008449 AK: Change ErrorOr to contain a Variant rather than inherit from it
GCC seems to get tripped up over this inheritance when converting from
an ErrorOr<StringView> to the partially specialized ErrorOr<void>. See
the following snippet:

    NEVER_INLINE ErrorOr<StringView> foo()
    {
        auto string = "abc"sv;
        outln("{:p}", string.characters_without_null_termination());
        return string;
    }

    NEVER_INLINE ErrorOr<void> bar()
    {
        auto string = TRY(foo());
        outln("{:p}", string.characters_without_null_termination());

        VERIFY(!string.starts_with('#'));
        return {};
    }

    int main()
    {
        MUST(bar());
    }

On some machines, bar() will contain a StringView whose pointer has had
its upper bits set to 0:

    0x000000010cafd6f8
    0x000000000cafd6f8

I'm not 100% clear on what's happening in the default-generated Variant
destructor that causes this. Probably worth investigating further.

The error would also be alleviated by making the Variant destructor
virtual, but rather than that, let's make ErrorOr simply contain a
Variant rather than inherit from it.

Fixes #15449.
2022-10-07 18:21:40 +01:00
Andreas Kling
da781e90c1 AK: Print VERIFY() error messages in release builds
Until now, VERIFY() failures would just cause a __builtin_trap() in
release builds, which made them a bit too harsh. This commit adds an
out-of-line helper function that prints the error before trapping.
2022-10-06 15:29:38 +02:00
Nico Weber
2af028132a AK+Everywhere: Add AK_COMPILER_{GCC,CLANG} and use them most places
Doesn't use them in libc headers so that those don't have to pull in
AK/Platform.h.

AK_COMPILER_GCC is set _only_ for gcc, not for clang too. (__GNUC__ is
defined in clang builds as well.) Using AK_COMPILER_GCC simplifies
things some.

AK_COMPILER_CLANG isn't as much of a win, other than that it's
consistent with AK_COMPILER_GCC.
2022-10-04 23:35:07 +01:00
Andreas Kling
74840c5537 AK: Add more AK_OS_FOO macros, including AK_OS_SERENITY 2022-10-02 21:14:02 +02:00
Daniel Bertalan
01c2cffcca AK: Fix naming conflict with compiler builtin
Clang patch D116203 added various builtin functions for type traits,
`__decay` being one of them. This name conflicts with our
`AK::Detail::__decay`, leading to compiler warnings with Clang 16.
2022-10-01 20:39:48 +02:00
Nico Weber
a934fa3d28 AK: Fix a comment typo 2022-09-30 20:09:26 -07:00
Diego Iastrubni
58a44036a9 Lagom: Fix printf implementation on win32
It seems that Filip has already done the hard work, and found out the
implementation different between unix* and windows.

Borrowed from:
https://github.com/SerenityOS/serenity/compare/master...filiphsps:serenity:dev-win32#diff-e3209c9a434a102d0d9459e31e33ddb729dff925b95f41b9d1e56c1e7f88c487R466

Co-authored-by: Filiph Sandström <filiph.sandstrom@filfatstudios.com>
2022-09-29 17:01:22 +01:00
Diego Iastrubni
18257604eb Lagom: Win32 support baby steps
This is the initial port of Lagom to win32. This will enable developers
to use Lagom as an alternative to vanilla STL/StandardC++Library - which
gives a much richer environment (think QtCore - but modern).

My main incentive - is to have a native Windows Ladybird working.

I am starting with AK, which does not yet fully compile (on mingw). When
AK is compiling (currently fails building StringBuffer.cpp) - I will
continue to LibCore and then the rest of the user space libraries
(excluding the GUI, which will be another different effort).

Most of the code is happily stollen from Andrew Kaster's fork - he
deserves the credit.

Co-authored-by: Andrew Kaster <akaster@serenityos.org>
2022-09-29 17:01:22 +01:00
networkException
4230dbbb21 AK+Everywhere: Replace "protocol" with "scheme" url helpers
URL had properly named replacements for protocol(), set_protocol() and
create_with_file_protocol() already. This patch removes these function
and updates all call sites to use the functions named according to the
specification.

See https://url.spec.whatwg.org/#concept-url-scheme
2022-09-29 09:39:04 +01:00
Timothy Flynn
5f9d8f25c6 AK+Meta: Define a debug flag for LibTimeZone 2022-09-28 23:52:51 +01:00
Lucas CHOLLET
42518867d7 AK: Make ErrorOr::error() const and return a const reference 2022-09-27 21:29:44 +01:00
Lucas CHOLLET
0396b6da82 AK: Add StringView operator==(char) 2022-09-27 21:29:44 +01:00
Linus Groh
edfef8e2f5 Everywhere: Rename WrapperGenerator to BindingsGenerator
This code generator no longer creates JS wrappers for platform objects
in the old sense, instead they're JS objects internally themselves.
Most of what we generate now are prototypes - which can be seen as
bindings for the internal C++ methods implementing getters, setters, and
methods - as well as object constructors, i.e. bindings for the internal
create_with_global_object() method.

Also tweak the naming of various CMake glue code existing around this.
2022-09-21 23:06:08 +01:00
Daniel Bertalan
2b69af2dfe AK+LibJS: Handle NaN-boxing pointers on AArch64
JS::Value stores 48 bit pointers to separately allocated objects in its
payload. On x86-64, canonical addresses have their top 16 bits set to
the same value as bit 47, effectively meaning that the value has to be
sign-extended to get the pointer. AArch64, however, expects the topmost
bits to be all zeros.

This commit gates sign extension behind `#if ARCH(X86_64)`, and adds an
`#error` for unsupported architectures, so that we do not forget to
think about pointer handling when porting to a new architecture.

Fixes #15290
Fixes SerenityOS/ladybird#56
2022-09-21 11:55:57 +02:00
Andreas Kling
287a9b552a AK: Fix bad parsing of some file:/// URLs with base URL
We were dropping the base URL path components in the resulting URL due
to mistakenly determining the input URL to start with a Windows drive
letter. Fix this, add a spec link, and a test.
2022-09-20 15:38:53 +02:00
Timothy Flynn
11bd6c3d68 AK: Do not require an allocated String for fuzzy matching
A StringView is sufficient here. This also removes the declaration of
fuzzy_match_recursive from the header, as it's only needed from within
the implementation file.
2022-09-20 11:08:54 +01:00
Ben Wiederhake
9c75d9e2cb AK: Move heavyweight fuzzy matching to own compilation unit 2022-09-18 13:27:24 -04:00
Tim Schumacher
643d2a683b AK: Define both ::nullptr_t and std::nullptr_t
LLVM 15 switched around what it's basing its `nullptr_t` definitions on,
it's now defining `std::nullptr_t` using `::nullptr_t` instead of the
other way around.

Work around any errors that result from that by just defining it both in
the global namespace as well as in `std` ourselves.
2022-09-16 05:39:28 +00:00
Lucas CHOLLET
62b8ccaffc StringBuilder: Add try_append_repeated() and append_repeated()
This two methods add the character as many times as specified by the
second parameter.
2022-09-15 14:08:21 +01:00
Sam Atkins
32c99313a6 AK: Warn when trying to set @foo@ as a SourceGenerator key
I was very confused why I was getting "no key named `foo`" errors, so
hopefully this will save someone that confusion in the future. :^)

(It'll probably be me again...)
2022-09-09 15:18:07 +02:00
Sam Atkins
edc3ed2a0e AK: Allow creating NonnullPtrVectors from an initializer list
This was present in Vector already. Clang-format fixed some const
positions automatically too.

Also removed a now-ambiguous and unnecessary constructor from Shell.
2022-09-08 18:53:08 +02:00
Andreas Kling
53c0038d2c AK: Make Weakable non-atomic
Let's not punish single-threaded workloads with the performance cost of
atomic weakables. The kernel keeps using LockWeakable.
2022-09-03 00:36:25 +02:00
davidot
75ebcf6b4a AK: Allow exponents in JSON double values
This is required for ECMA-404 compliance, but probably not for serenity
itself.
2022-09-02 02:07:37 +01:00
Liav A
13c8695523 AK: Add find_first_split_view() helper for StringView container
Similar to the find_last_split_view() helper, but in this helper we
search for the first split view instead of the last one.
2022-08-30 00:50:15 +01:00
Jelle Raaijmakers
8483064b59 AK: Add FloatingPoint.h
This is a set of functions that allow you to convert between arbitrary
IEEE 754 floating point types, as long as they can be represented
within 64 bits. Conversion methods between floats and doubles are
provided, as well as a generic `float_to_float()`.

Example usage:

  #include <AK/FloatingPoint.h>

  double val = 1.234;
  auto weird_f16 =
      convert_from_native_double<FloatingPointBits<0, 6, 10>>(val);

Signed and unsigned floats are supported, and both NaN and +/-Inf are
handled correctly. Values that do not fit in the target floating point
type are clamped.
2022-08-27 12:28:05 +02:00
Andreas Kling
f03f70a84a AK: Make empty FixedArray smaller
Move the FixedArray's size field into the heap-allocated storage. This
makes zero-sized FixedArrays take up 8 bytes instead of 16.
2022-08-27 12:19:37 +02:00
Andreas Kling
11eee67b85 Kernel: Make self-contained locking smart pointers their own classes
Until now, our kernel has reimplemented a number of AK classes to
provide automatic internal locking:

- RefPtr
- NonnullRefPtr
- WeakPtr
- Weakable

This patch renames the Kernel classes so that they can coexist with
the original AK classes:

- RefPtr => LockRefPtr
- NonnullRefPtr => NonnullLockRefPtr
- WeakPtr => LockWeakPtr
- Weakable => LockWeakable

The goal here is to eventually get rid of the Lock* classes in favor of
using external locking.
2022-08-20 17:20:43 +02:00
Andreas Kling
e475263113 AK+Kernel: Add AK::AtomicRefCounted and use everywhere in the kernel
Instead of having two separate implementations of AK::RefCounted, one
for userspace and one for kernelspace, there is now RefCounted and
AtomicRefCounted.
2022-08-20 17:15:52 +02:00
kleines Filmröllchen
4809dc8ec2 AK: Add Singleton special-case constructor for SpinlockProtected
This will allow Singletons of that class to still be created when
SpinlockProtected can't be constructed without a lock rank argument
anymore.
2022-08-19 20:26:47 -07:00
davidot
8be96cd7ff AK: Allow bit_cast to be used in constant evaluated context 2022-08-15 17:11:25 +02:00
thankyouverycool
75b6097c55 AK: Add human_readable_digital_time() helper
Converts seconds into a readable digital format. For example:
30 seconds	= "00:30"
90 seconds	= "01:30"
86401 seconds	= "24:00:01"
And so on.
2022-08-05 13:55:13 +02:00
Andreas Kling
b6307f73a2 AK: Suppress -Wunqualified-std-cast-call in the CLion IDE 2022-08-05 12:42:46 +02:00
Brian Gianforcaro
ea9ef33a7f AK: Prefix CACHE_ALIGNED & SYSTEM_CACHE_ALIGNMENT_SIZE 2022-08-01 00:19:16 +02:00
Filiph Sandström
5a281336c5 AK: Fix usage of undefined variables
The commit that introduced BuiltinWrappers (548529a) accidentally used
`val` instead of `value` in the non `__GNUC__` and `__clang__` versions
of the functions.
2022-07-31 11:08:33 +02:00
MacDue
13406b83b1 AK: VERIFY() the index is in bounds in StringView::operator[]
That this did not already happen took me by surprise, as for
most other similar containers/types in AK (e.g. Span) the index
will be checked. This check not happening could easily let
off-by-one indexing errors slip through the cracks.
2022-07-26 12:41:46 +02:00
Linus Groh
8150d71821 Everywhere: Prefix 'TYPEDEF_DISTINCT_ORDERED_ID' with 'AK_' 2022-07-22 23:09:43 +01:00
Linus Groh
5a106b6401 Everywhere: Prefix 'TYPEDEF_DISTINCT_NUMERIC_GENERAL' with 'AK_' 2022-07-22 23:09:43 +01:00
kleines Filmröllchen
500dc83f32 AK: Add FixedArray::fill_with
This is a memset-like utility method.
2022-07-22 19:35:41 +01:00
kleines Filmröllchen
5b1345a4ff AK: Remove FixedArray::must_create_but_fixme_should_propagate_errors
Nobody was using this anymore.
2022-07-22 19:35:41 +01:00
Samuel Bowman
25de9de7dc Kernel+LibPartition: Move GUIDPartitionTable into LibPartition 2022-07-21 20:13:44 +01:00
Samuel Bowman
1a6ef03e4a Kernel+LibPartition: Move MBRPartitionTable into LibPartition 2022-07-21 20:13:44 +01:00
Daniel Bertalan
42e22f89a4 AK+LibGfx+LibJS: Pass -1 as the file descriptor to anonymous mmap
Serenity/Linux/macOS ignore the file descriptor when an anonymous
mapping is requested. However, BSDs require the fd to be -1.
2022-07-19 12:39:24 +02:00
Daniel Bertalan
ae4d871183 AK: Port StackInfo to FreeBSD
This can almost be identical to the Linux version, except that the
`pthread_attr_t` object is populated using a call to
`pthread_attr_get_np` instead of `pthread_getattr_np`.

FreeBSD also needs `pthread_atttr_t` to be initialized using
`pthread_attr_init` instead of zero-initialization, but it's the
technically correct thing to do on Linux as well.
2022-07-19 12:39:24 +02:00
Daniel Bertalan
cd0fb6dcc8 AK: Do not negate Pthread error codes for strerror()
On all systems I've checked, pthread functions return the positive error
code directly.
2022-07-19 12:39:24 +02:00
Andrew Kaster
3b15addbc8 AK: Add support for building on Android with API version >= 30 2022-07-19 10:44:02 +01:00
Hendiadyoin1
154871834b AK: Add a helper to get the last split-group 2022-07-15 12:42:43 +02:00
Ali Mohammad Pur
0d6dc74951 AK: Use the correct data types in bitap_bitwise()
Otherwise the bit twiddling goes all wrong and breaks some boundary
cases.
Fixes `StringView::contains(31-chars)`.
2022-07-14 13:10:23 +02:00
Linus Groh
3953004e60 AK: Add Traits<ByteBuffer>::hash() 2022-07-14 00:42:26 +01:00
sin-ack
5744211001 AK: Remove StringView(char const*) :^)
This constructor relied on running strlen implicitly on its argument,
thereby potentially causing out-of-bound reads (some of which were
caught a few days ago). The removal of this constructor ensures that the
caller must explicitly pass the size of the string by either:

1) Using operator""sv on literal strings; or
2) Calling strlen explicitly, making it clear that the size of the view
   is being calculated at runtime.
2022-07-12 23:11:35 +02:00
sin-ack
604aac531c AK+Userland+Tests: Remove URL(char const*) constructor
The StringView(char const*) constructor is being removed, and there was
only a few users of this left, which are also cleaned up in this commit.
2022-07-12 23:11:35 +02:00
sin-ack
3f8060d859 AK: Remove String <-> char const* comparison operators
During the removal of StringView(char const*), all users of these
functions were removed, and they are of dubious value (relying on
implicit StringView conversion).
2022-07-12 23:11:35 +02:00
sin-ack
c8585b77d2 Everywhere: Replace single-char StringView op. arguments with chars
This prevents us from needing a sv suffix, and potentially reduces the
need to run generic code for a single character (as contains,
starts_with, ends_with etc. for a char will be just a length and
equality check).

No functional changes.
2022-07-12 23:11:35 +02:00
sin-ack
3f3f45580a Everywhere: Add sv suffix to strings relying on StringView(char const*)
Each of these strings would previously rely on StringView's char const*
constructor overload, which would call __builtin_strlen on the string.
Since we now have operator ""sv, we can replace these with much simpler
versions. This opens the door to being able to remove
StringView(char const*).

No functional changes.
2022-07-12 23:11:35 +02:00
sin-ack
e5f09ea170 Everywhere: Split Error::from_string_literal and Error::from_string_view
Error::from_string_literal now takes direct char const*s, while
Error::from_string_view does what Error::from_string_literal used to do:
taking StringViews. This change will remove the need to insert `sv`
after error strings when returning string literal errors once
StringView(char const*) is removed.

No functional changes.
2022-07-12 23:11:35 +02:00
sin-ack
c70f45ff44 Everywhere: Explicitly specify the size in StringView constructors
This commit moves the length calculations out to be directly on the
StringView users. This is an important step towards the goal of removing
StringView(char const*), as it moves the responsibility of calculating
the size of the string to the user of the StringView (which will prevent
naive uses causing OOB access).
2022-07-12 23:11:35 +02:00
sin-ack
7da00bfa8d AK: Add string literal helpers to AK::SourceGenerator
Since all uses of SourceGenerator are with literal strings, there is no
need to burden generators with the sv suffix.
2022-07-12 23:11:35 +02:00
sin-ack
6eecc65787 AK: Explicitly calculate length of char* when printing
This moves out the calculation of the char* out to the formatter.
Additionally, we now print (null) when a null pointer is passed.
2022-07-12 23:11:35 +02:00
sin-ack
52d017c611 AK: Make CheckedFormatString pass the char array size to StringView
This makes the assumption that we never pass a stack-allocated char
array to CheckedFormatString arguments (dbgln, outln, warnln). This
assumption seems to hold true for the current state of Serenity code, at
least. :^)
2022-07-12 23:11:35 +02:00
Luke Wilde
da25ac0d48 AK: Treat empty string as invalid JSON
Previously we would treat the empty string as `null`. This caused
JavaScript like this to fail:
```js
var object = {};
try {
    object = JSON.parse("");
} catch {}
var array = object.array || [];
```
Since `JSON.parse("")` returned null instead of throwing, it would set
`object` to null and then try and use it instead of using the default
backup value.
2022-07-10 23:31:48 +02:00
Karol Kosek
b5420b8a9a LibGfx: Implement PNG filtering on write
Is it another great upgrade to our PNG encoder like in 9aafaec259?
Well, not really - it's not a 2x or 55x improvement like you saw there,
but still it saves something:

- a screenshot of a blank Serenity desktop dropped from about 45 KiB
  to 40 KiB.
- re-encoding NASA photo of the Earth to PNG again saves about 25%
  (16.5 MiB -> 12.3 MiB), compared to not using filters.

[1]: https://commons.wikimedia.org/wiki/File:The_Blue_Marble_(remastered).jpg
2022-07-10 15:01:07 +02:00
kleines Filmröllchen
41b2d37e8a AK: Always check shift amount in LEB128 read functions
Even shifting 0 by more than the value size is UB.
2022-07-09 22:04:31 +00:00
Andreas Kling
2217d91b8d AK: Make VERIFY() work in MinSizeRel builds 2022-07-09 22:15:43 +02:00
Allan Regush
63d06458ca AK: Add equality operators to compare RefPtr to NonNullRefPtr 2022-07-09 09:32:51 +01:00
Allan Regush
ce7d868d6b AK: Add comparison operators to NonnullRefPtr 2022-07-09 09:32:51 +01:00
Maciej
36676a1604 AK: Add IPv4Address::netmask_from_cidr 2022-07-09 09:22:25 +01:00
DexesTTP
7ceeb74535 AK: Use an enum instead of a bool for String::replace(all_occurences)
This commit has no behavior changes.

In particular, this does not fix any of the wrong uses of the previous
default parameter (which used to be 'false', meaning "only replace the
first occurence in the string"). It simply replaces the default uses by
String::replace(..., ReplaceMode::FirstOnly), leaving them incorrect.
2022-07-06 11:12:45 +02:00
Idan Horowitz
33214c29d3 AK: Add an align_down_to power of two helper
Matching the similar align_up_to helper
2022-07-05 11:26:10 +02:00
FrHun
dba6f0bc4b AK: Add header for generic shorthands
These are functions that can be expressed with just normal operators,
but would be very repetetive.
2022-07-04 11:15:40 +02:00
Lenny Maiorani
c860d8f5be AK: Add nodiscard attribute to Find functions 2022-07-04 05:53:56 +00:00
Lenny Maiorani
ef4b98be52 AK: Add nodiscard attribute to BitStream functions 2022-07-04 05:53:56 +00:00
Lenny Maiorani
97d966d25c AK: Add nodiscard attribute to BitCast functions 2022-07-04 05:53:56 +00:00
Lenny Maiorani
84d9e537cd AK: Add nodiscard attribute to BinarySearch functions 2022-07-04 05:53:56 +00:00
Lenny Maiorani
ccbf240962 AK: Add nodiscard attribute to BinaryHeap functions 2022-07-04 05:53:56 +00:00
Lenny Maiorani
56cabf80de AK: Add nodiscard attribute to Base64 functions 2022-07-04 05:53:56 +00:00
Lenny Maiorani
49042bffe9 AK: Add nodiscard attribute to AnyOf functions 2022-07-04 05:53:56 +00:00
Lenny Maiorani
318bee03d8 AK: Add nodiscard attribute to AllOf functions 2022-07-04 05:53:56 +00:00
MacDue
072a78b958 AK: Add AK::ceil(float) and AK::ceil_log2(integer)
Co-authored-by: Leon Albrecht <leon2002.la@gmail.com>
2022-06-30 11:16:22 +02:00
Lucas CHOLLET
3843b8c0a1 AK: Perform a resize in ByteBuffer::get_bytes_for_writing()
ByteBuffer::get_bytes_for_writing() was only ensuring capacity before
this patch. The method needs to call resize to register the appended
data, otherwise it will be overwritten with next data addition.
2022-06-27 20:22:15 +01:00
Ali Mohammad Pur
2104e9a6e4 AK: Recognize __CLION_IDE__ as well as __CLION_IDE_
This used to be `__CLION_IDE_` before, but it seems to have been fixed
in the latest EAP.
2022-06-26 22:21:17 +01:00
kleines Filmröllchen
07d712ea00 AK: Add saturating addition and subtraction to Checked 2022-06-23 23:26:33 +01:00
Hendiadyoin1
5bf84a5b0e AK: Zero previous pointer *after* fixing the insertion list in HashTable 2022-06-23 20:25:12 +03:00
Idan Horowitz
eb02425ef9 AK: Clear the previous and next pointers of deleted HashTable buckets
Usually the values of the previous and next pointers of deleted buckets
are never used, as they're not part of the main ordered bucket chain,
but if an in-place rehashing is done, which results in the bucket being
turned into a free bucket, the stale pointers will remain, at which
point any item that is inserted into said free-bucket will have either
a stale previous pointer if the HashTable was empty on insertion, or a
stale next pointer, resulting in undefined behaviour.

This commit also includes a new HashMap test that reproduces this issue
2022-06-22 21:53:13 +02:00
Linus Groh
9e79856b43 Revert "AK: Add comparison operators to NonnullOwnPtr"
This reverts commit 50c88e5e3a.

The intention was to add them to NonnullRefPtr, not NonnullOwnPtr. That
is also what was advertised in the PR, but not actually done in the
reverted commit.
2022-06-18 13:17:49 +01:00
Allan Regush
50c88e5e3a AK: Add comparison operators to NonnullOwnPtr 2022-06-18 02:11:08 +01:00
Andreas Kling
75dca629df AK+Kernel: Remove RefPtrTraits template param in userspace code
Only the kernel actually uses RefPtrTraits, so let's not burden
userspace builds with the complexity.
2022-06-15 17:15:04 +02:00
Andreas Kling
9e994da2ac Kernel+AK: Split Weakable.h into userspace and kernel variants
Only the kernel expects AK::Weakable to lock its refcount manipulation,
so let's not force userspace to pay for that as well.
2022-06-15 17:15:04 +02:00
Hediadyoin1
e6a3cac5ce AK: Add sqrt(2) and sqrt(1/2) constants 2022-06-14 23:00:52 +02:00
Luke Wilde
076c9772a4 LibWeb: Add ability to present LibGL framebuffer and add clearing 2022-06-13 21:45:27 +01:00
Matthias Zimmerman
c10d48b72c AK/ByteBuffer+Everywhere: Handle errors in ByteBuffer::slice() 2022-06-13 15:38:51 +01:00
Karol Kosek
65afa113e5 AK: Make URL ApplicationXWWWFormUrlencoded encoding closer to spec
It was mostly implemented based on a spec note, that described only
allowed characters, but instead of allowing some special characters not
to be escaped, we escaped every special character except those 'new in
this encode set' disallowed characters from the spec definition.
2022-06-10 22:32:29 +01:00
Karol Kosek
9e69a89f8e AK: Append correct number of port characters when serializing a URL
Instead of formatting a port string, it put bytes from stack, using the
port number as a length (so for port 8000 it appended 8000 bytes).
2022-06-10 22:32:29 +01:00
Tim Schumacher
b3e0aed91f AK: Add SinglyLinkedList::prepend() 2022-06-10 19:06:46 +01:00
Lucas CHOLLET
dad4716cc2 AK: Add Error::operator==(Error const&) 2022-06-09 22:08:04 +02:00
huttongrabiel
8ffa860bc3 AK: Add invert_case() and invert_case(StringView)
In the given String, invert_case() swaps lowercase characters with
uppercase ones and vice versa.
2022-05-26 21:51:23 +01:00
Ali Mohammad Pur
06c6c046f3 AK: Use static_cast to cast to base type
This is an issue on systems that don't have the empty base class
optimisation (such as windows), and we normally don't need to care -
however static_cast is technically the right thing to use, so let's use
that instead.

Co-Authored-By: Daniel Bertalan <dani@danielbertalan.dev>
2022-05-21 02:18:40 +02:00
Daniel Bertalan
014b9fd709 AK+DHCPClient: Fix false positive gcc 12 warnings
The compiler would complain about `__builtin_memcpy` in ByteBuffer::copy
writing out of bounds, as it isn't able to deduce the invariant that the
inline buffer is only used when the requested size is smaller than the
inline capacity.

The other change is more bizarre. If the destructor's declaration
exists, gcc complains about a `delete` operation causing an
out-of-bounds array access.

error: array subscript 'DHCPv4Client::__as_base [0]' is partly outside
array bounds of 'unsigned char [8]' [-Werror=array-bounds]
   14 |   ~DHCPv4Client() = default;
      |   ^

This looks like a compiler bug, and I'll report it if I find a suitable
reduced reproducer.
2022-05-12 13:12:37 +02:00
Jelle Raaijmakers
2c381ea45c AK: Add clamp(f32x4, float, float)
We are allowed to directly compare `f32x4` with a `float`, so make use
of it.
2022-05-09 21:49:48 +02:00
Vitaly Dyachkov
a0a4d169f4 AK+LibGUI: Pass predicate to *_matching() methods by const reference 2022-05-08 17:02:00 +02:00
EWouters
0317882b61 AK: Use AK:: sin and cos on aarch64 build
This fixes the lagom build on aarch64, as `__builtin_sincosf` doesn't
take double arguments.
2022-05-08 16:51:23 +02:00
EWouters
6ea89c35fe AK: Use builtin versions of llrint{,l,f}
This fixes the build on M1 Macs.
2022-05-07 23:36:49 +02:00
Hendiadyoin1
d4fe02152a AK: Add an SSE2 specific implementation of sqrt(double) 2022-05-07 20:27:05 +02:00
Hendiadyoin1
6d9bc87903 AK: Add a cpp-y, more fine grained version of fenv.h: FPControl.h
This allows direct inlining and hides away some assembly and
bit-fiddling when manipulating the floating point environment.

This only implements the x87/SSE versions, as of now.
2022-05-07 20:27:05 +02:00
Hendiadyoin1
37ff2b9bd2 AK: Add an helper for quick hardware based rounding
This uses the `fistp` and `cvts[sd]2si` respectively, to potentially
round floating point values with just one instruction.

This falls back to `llrint[fl]?` on aarch64 for now.
2022-05-07 20:25:39 +02:00
kleines Filmröllchen
df57536c40 AK: Put invalid UTF8 debug spam behind a flag
This is very annoying if we're (intentionally) passing invalid UTF8 into
Utf8View.
2022-04-27 00:02:24 +02:00
Andrew Kaster
83603d68d2 AK: Make sure we don't include Math.h or math.h from KERNEL 2022-04-23 10:43:32 -07:00
kleines Filmröllchen
6b13436ef6 LibCore: Introduce SharedSingleProducerCircularQueue
This new class with an admittedly long OOP-y name provides a circular
queue in shared memory. The queue is a lock-free synchronous queue
implemented with atomics, and its implementation is significantly
simplified by only accounting for one producer (and multiple consumers).
It is intended to be used as a producer-consumer communication
datastructure across processes. The original motivation behind this
class is efficient short-period transfer of audio data in userspace.

This class includes formal proofs of several correctness properties of
the main queue operations `enqueue` and `dequeue`. These proofs are not
100% complete in their existing form as the invariants they depend on
are "handwaved". This seems fine to me right now, as any proof is better
than no proof :^). Anyways, the proofs should build confidence that the
implemented algorithms, which are only roughly based on existing work,
operate correctly in even the worst-case concurrency scenarios.
2022-04-21 13:55:00 +02:00
kleines Filmröllchen
65b338ad04 AK: Allow alignment to cache line size with CACHE_ALIGNED
This is particularly important to avoid false sharing, which thrashes
performance when two process-shared atomics are on the same cache line.
2022-04-21 13:55:00 +02:00
Tim Schumacher
908d5a2853 AK: Expose RedBlackTree::find_smallest_not_below() 2022-04-21 13:16:56 +02:00
ForLoveOfCats
79a2088a13 AK: Make Vector::contains_slow templated
This allows for calling this function with any argument type for which
the appropriate traits and operators have been implemented so it can be
compared to the Vector's item type
2022-04-21 09:12:37 +04:30
ForLoveOfCats
a7fe3183f5 AK: Add URL::create_with_help_scheme helper function 2022-04-21 09:12:37 +04:30
faxe1008
b8bd667782 AK: Add FuzzyMatch header
This patch adds a header containing the fuzzy match algorithm
previously used in Assistant. The algorithm was moved to AK
since there are many places where a search may benefit from fuzzyness.
2022-04-20 18:34:09 +02:00
Ali Mohammad Pur
dd370fcdd1 AK: Explicitly instantiate String::to_uint<unsigned long{, long}>()
Instead of just to_uint<u64>().
2022-04-20 00:15:23 +04:30
Ali Mohammad Pur
2b79f36148 AK: Add a OneOfIgnoringCV concept
Some functions want to ignore cv-qualifiers, and it's much easier to
constrain the type through a concept than a separate requires clause on
the function.
2022-04-20 00:15:23 +04:30
Thitat Auareesuksakul
f4b8bae65f AK: Add Kernel namespace to KStrings in AK::IPv6Address
Currently there is no AK::IPv6Address in the kernel. But when there is,
KStrings won't resolve properly because they are in Kernel namespace.
2022-04-17 16:57:52 -07:00
Tim Schumacher
d6ccee4089 AK: Differ between long and long long formats 2022-04-14 03:12:56 +04:30
Tim Schumacher
fbfa378e74 AK: Deduplicate formatting hexadecimal values
Both calls essentially only differ in one boolean, which dictates
whether to print the value in uppercase or lowercase.

Move the long function call into a new function and pass in the
"uppercase" boolean seperately to avoid having to write everything
twice.
2022-04-14 03:12:56 +04:30
Tim Schumacher
0d5098fdc0 AK: Merge print_i64 into print_signed_number
Those functions only differ by the input type of `number`. No other
wrapper does this, as they rely on adjusting the type of the argument on
the caller side instead.

Avoid specializing too much by just doing the same for signed numbers.
2022-04-14 03:12:56 +04:30
Andreas Kling
83082b12b7 LibWeb: Make reverse iterators work for const NonnullPtrVectors 2022-04-13 19:52:25 +02:00
Andreas Kling
40f584a2bb AK: Add missing include to Traits.h 2022-04-10 19:18:16 +02:00
Andreas Kling
ae6b09f4dc AK: Add hash traits for floating-point primitives
This allows us to use float and double as hash keys.
2022-04-10 12:39:44 +02:00
Jelle Raaijmakers
1577a8ba42 AK: Remove KERNEL check from String
Since we no longer use `String` inside of the kernel code, we can drop
this `#ifndef`.
2022-04-10 12:08:31 +02:00